diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fa17c24 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +cache/* +cache/**/* +test/* +test/**/* +Smarty/templates_c/* +storage/* +storage/**/* +logs/* +backup/* +user_privileges/* +config-dev.inc.php diff --git a/Popup.php b/Popup.php index 20f7c04..7229887 100644 --- a/Popup.php +++ b/Popup.php @@ -131,6 +131,8 @@ switch($currentModule) break; case 'Vendors': $smarty->assign("SINGLE_MOD",'Vendor'); + if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] !='') + $smarty->assign("RETURN_MODULE",vtlib_purify($_REQUEST['return_module'])); $alphabetical = AlphabeticalSearch($currentModule,'Popup','vendorname','true','basic',$popuptype,"","",$url); break; case 'SalesOrder': diff --git a/Smarty/templates/Buttons_List.tpl b/Smarty/templates/Buttons_List.tpl index 7698e28..777aca9 100644 --- a/Smarty/templates/Buttons_List.tpl +++ b/Smarty/templates/Buttons_List.tpl @@ -116,7 +116,7 @@ {if $MODULE eq 'Contacts' || $MODULE eq 'Leads' || $MODULE eq 'Accounts'|| $MODULE eq 'Products'|| $MODULE eq 'Potentials'|| $MODULE eq 'HelpDesk'|| $MODULE eq 'Vendors' || $CUSTOM_MODULE eq 'true'} {if $CHECK.DuplicatesHandling eq 'yes'} - {$APP.LBL_FIND_DUPICATES} + {$APP.LBL_FIND_DUPLICATES} {else} {/if} diff --git a/Smarty/templates/ComposeEmail.tpl b/Smarty/templates/ComposeEmail.tpl index be7232f..1c1dbc1 100644 --- a/Smarty/templates/ComposeEmail.tpl +++ b/Smarty/templates/ComposeEmail.tpl @@ -17,7 +17,7 @@ {$MOD.TITLE_COMPOSE_MAIL} - + diff --git a/Smarty/templates/CustomView.tpl b/Smarty/templates/CustomView.tpl index 1681f99..7f18783 100644 --- a/Smarty/templates/CustomView.tpl +++ b/Smarty/templates/CustomView.tpl @@ -576,6 +576,7 @@ function mandatoryCheck()
+
diff --git a/Smarty/templates/DetailView.tpl b/Smarty/templates/DetailView.tpl index e4424c8..7960cf3 100755 --- a/Smarty/templates/DetailView.tpl +++ b/Smarty/templates/DetailView.tpl @@ -222,7 +222,7 @@ function sendfile_email() id="More_Information_Modules_List" class="drop_mnu" style="left: 502px; top: 76px; display: none;"> {foreach key=_RELATION_ID item=_RELATED_MODULE from=$IS_REL_LIST} - + {/foreach}
{$_RELATED_MODULE|@getTranslatedString:$MODULE}
{$_RELATED_MODULE|@getTranslatedString:$_RELATED_MODULE}
@@ -446,7 +446,7 @@ function sendfile_email() {/if} - {elseif $TODO_PERMISSION eq 'true' || $EVENT_PERMISSION eq 'true' || $CONTACT_PERMISSION eq 'true'|| $MODULE eq 'Contacts' || ($MODULE eq 'Documents')} + {elseif $TODO_PERMISSION eq 'true' || $EVENT_PERMISSION eq 'true' || $CONTACT_PERMISSION eq 'true'|| $MODULE eq 'Contacts' || $MODULE eq 'Leads' || ($MODULE eq 'Documents')} {if $MODULE eq 'Contacts'} {assign var=subst value="contact_id"} diff --git a/Smarty/templates/DetailViewFields.tpl b/Smarty/templates/DetailViewFields.tpl index e6fc6b4..50b1e8e 100644 --- a/Smarty/templates/DetailViewFields.tpl +++ b/Smarty/templates/DetailViewFields.tpl @@ -140,33 +140,22 @@ {$keyval}  {elseif $keyid eq 83} - - {$APP.LBL_VAT} {$APP.COVERED_PERCENTAGE} - -   - {$VAT_TAX} - -   - - - - {$APP.LBL_SALES} {$APP.LBL_TAX} {$APP.COVERED_PERCENTAGE} - -   - {$SALES_TAX} - -   - - - - {$APP.LBL_SERVICE} {$APP.LBL_TAX} {$APP.COVERED_PERCENTAGE} - -   - {$SERVICE_TAX} - + {foreach item=tax key=count from=$TAX_DETAILS} + + {$tax.taxlabel} {$APP.COVERED_PERCENTAGE} + + + + {$tax.percentage} + +   + + {/foreach} {elseif $keyid eq 69} -  {$keyval} +  {$keyval} + {elseif $keyid eq 10} +  {$keyval} {else} -  {$keyval} +  {$keyval} {/if} diff --git a/Smarty/templates/DetailViewUI.tpl b/Smarty/templates/DetailViewUI.tpl index 218ad41..e02045c 100644 --- a/Smarty/templates/DetailViewUI.tpl +++ b/Smarty/templates/DetailViewUI.tpl @@ -14,7 +14,7 @@ {if $keyid eq '1' || $keyid eq 2 || $keyid eq '11' || $keyid eq '7' || $keyid eq '9' || $keyid eq '55' || $keyid eq '71' || $keyid eq '72' || $keyid eq '103' || $keyid eq '255' || $keyid eq '14'} - + {if $keyid eq '55' || $keyid eq '255'} {if $keyaccess eq $APP.LBL_NOT_ACCESSIBLE} {$APP.LBL_NOT_ACCESSIBLE} @@ -210,7 +210,7 @@ {elseif $keyid eq '50' || $keyid eq '73' || $keyid eq '51'}  {$keyval} - {elseif $keyid eq '57'} + {elseif $keyid eq '57' || $keyid eq '58'}  {$keyval} {elseif $keyid eq '59'} @@ -374,7 +374,9 @@ {elseif $keyid eq 69} -  {$keyval} +  {$keyval} + {elseif $keyid eq 10} +  {$keyval} {else} -  {$keyval} +  {$keyval} {/if} diff --git a/Smarty/templates/DocumentsListViewEntries.tpl b/Smarty/templates/DocumentsListViewEntries.tpl index 3a76643..e9ba5f7 100644 --- a/Smarty/templates/DocumentsListViewEntries.tpl +++ b/Smarty/templates/DocumentsListViewEntries.tpl @@ -230,7 +230,7 @@ {$MODULE_CREATE} {/if} {$APP.LBL_NOW}. {$APP.LBL_CLICK_THE_LINK}:
-   -{$APP.LBL_CREATE} {$APP.$vowel_conf} {$MOD.$MODULE_CREATE} +   -{$APP.LBL_CREATE} {$APP.$vowel_conf} {$APP.$MODULE_CREATE} diff --git a/Smarty/templates/EmailDetailView.tpl b/Smarty/templates/EmailDetailView.tpl index f86bde7..1c73307 100755 --- a/Smarty/templates/EmailDetailView.tpl +++ b/Smarty/templates/EmailDetailView.tpl @@ -15,7 +15,7 @@ {$MOD.TITLE_VTIGERCRM_MAIL} - + diff --git a/Smarty/templates/Header.tpl b/Smarty/templates/Header.tpl index 1443b24..47cd890 100644 --- a/Smarty/templates/Header.tpl +++ b/Smarty/templates/Header.tpl @@ -13,7 +13,7 @@ {$USER} - {$MODULE_NAME|@getTranslatedString:$MODULE_NAME} - {$APP.LBL_BROWSER_TITLE} - + {* vtlib customization: Inclusion of custom javascript and css as registered *} @@ -87,7 +87,7 @@ - +
{$LOGO}{$COMPANY_DETAILS.name}
@@ -118,12 +118,12 @@ {$USER} {* ondemand customization: Header links on the top panel *} - + {* END *} {* vtlib customization: Header links on the top panel *} {if $HEADERLINKS} - @@ -625,14 +626,6 @@ function getFormValidate(divValidate) - - - - - - +
{$APP.LNK_HELP}
{$APP.LBL_FEEDBACK} {$APP.LNK_HELP}
@@ -698,14 +688,6 @@ function openwin() {/foreach}
- - +{if $RETURN_MODULE != ''} +{/if} @@ -102,15 +104,15 @@ function set_focus() {ldelim} {if $recid_var_value neq ''} - + {else} {if $RECORD_ID} - + {else} - + {/if} {/if} - +
{$APP[$MODULE]} {$APP.LBL_RELATED_TO} {$APP[$PARENT_MODULE]}{$MODULE|@getTranslatedString:$MODULE} {$APP.LBL_RELATED_TO} {$PARENT_MODULE|@getTranslatedString:$PARENT_MODULE}{$APP[$MODULE]} > {$PRODUCT_NAME}{$MODULE|@getTranslatedString:$MODULE} > {$PRODUCT_NAME}{$APP[$MODULE]}{$MODULE|@getTranslatedString:$MODULE}{$APP.VTIGER}{'APP_NAME'|@getTranslatedString}
diff --git a/Smarty/templates/PrintEmail.tpl b/Smarty/templates/PrintEmail.tpl index 9a2cc1b..f9ac487 100644 --- a/Smarty/templates/PrintEmail.tpl +++ b/Smarty/templates/PrintEmail.tpl @@ -16,7 +16,7 @@ {$MOD.TITLE_VTIGERCRM_MAIL} - + diff --git a/Smarty/templates/RelatedListContents.tpl b/Smarty/templates/RelatedListContents.tpl index b850d52..a464714 100644 --- a/Smarty/templates/RelatedListContents.tpl +++ b/Smarty/templates/RelatedListContents.tpl @@ -76,7 +76,7 @@ function loadRelatedListBlock(urldata,target,imagesuffix) { } }else{ $(imagesuffix+'_linkForSelectAll').hide(); - rel_toggleSelect(false,imagesuffix+'_selected_id',relatedModule); + //rel_toggleSelect(false,imagesuffix+'_selected_id',relatedModule); } updateParentCheckbox(obj,imagesuffix); } diff --git a/Smarty/templates/RolePopup.tpl b/Smarty/templates/RolePopup.tpl index d757bdc..74cfef5 100755 --- a/Smarty/templates/RolePopup.tpl +++ b/Smarty/templates/RolePopup.tpl @@ -51,7 +51,7 @@
- +
{$CMOD.LBL_ASSIGN_ROLE}{$APP.VTIGER}{'APP_NAME'|@getTranslatedString}
diff --git a/Smarty/templates/Settings/CustomModEntityNo.tpl b/Smarty/templates/Settings/CustomModEntityNo.tpl index 53cdc37..6240333 100644 --- a/Smarty/templates/Settings/CustomModEntityNo.tpl +++ b/Smarty/templates/Settings/CustomModEntityNo.tpl @@ -154,9 +154,7 @@ function updateModEntityExisting(button, form) { {assign var = "selected_val" value=""} {/if} {assign var="MODULE_LABEL" value=$value} - {if $APP.$value neq ''} - {assign var="MODULE_LABEL" value=$APP.$value} - {/if} + {assign var="MODULE_LABEL" value=$value|getTranslatedString:$value} {/foreach} diff --git a/Smarty/templates/Settings/ModuleManager/ModuleManagerAjax.tpl b/Smarty/templates/Settings/ModuleManager/ModuleManagerAjax.tpl index 46b2ee5..d8a9542 100644 --- a/Smarty/templates/Settings/ModuleManager/ModuleManagerAjax.tpl +++ b/Smarty/templates/Settings/ModuleManager/ModuleManagerAjax.tpl @@ -53,7 +53,7 @@ function vtlib_modulemanager_toggleTab(shownode, hidenode, highlighttab, dehighl {if $modinfo.customized eq true} {assign var="totalCustomModules" value=$totalCustomModules+1} - {assign var="modulelabel" value=$modulename} + {assign var="modulelabel" value=$modulename|getTranslatedString:$modulename} {if $APP.$modulename}{assign var="modulelabel" value=$APP.$modulename}{/if} diff --git a/Smarty/templates/ShowAuditTrail.tpl b/Smarty/templates/ShowAuditTrail.tpl index fa8e658..149d4da 100644 --- a/Smarty/templates/ShowAuditTrail.tpl +++ b/Smarty/templates/ShowAuditTrail.tpl @@ -23,7 +23,7 @@ - +
{$MOD.LBL_AUDIT_TRAIL}{$APP.VTIGER}{'APP_NAME'|@getTranslatedString}
diff --git a/Smarty/templates/com_vtiger_workflow/EditWorkflow.tpl b/Smarty/templates/com_vtiger_workflow/EditWorkflow.tpl index e9bdb4f..88fe948 100644 --- a/Smarty/templates/com_vtiger_workflow/EditWorkflow.tpl +++ b/Smarty/templates/com_vtiger_workflow/EditWorkflow.tpl @@ -12,7 +12,7 @@ {include file='SetMenu.tpl'}
{include file='com_vtiger_workflow/ModuleTitle.tpl'} -
+ {include file='com_vtiger_workflow/EditWorkflowMeta.tpl'} {include file='com_vtiger_workflow/EditWorkflowBasicInfo.tpl'} diff --git a/Smarty/templates/com_vtiger_workflow/taskforms/VTEmailTask.tpl b/Smarty/templates/com_vtiger_workflow/taskforms/VTEmailTask.tpl index ddc6321..dd4b457 100644 --- a/Smarty/templates/com_vtiger_workflow/taskforms/VTEmailTask.tpl +++ b/Smarty/templates/com_vtiger_workflow/taskforms/VTEmailTask.tpl @@ -44,7 +44,7 @@ var moduleName = '{$entityName}'; + {if $MODULE eq 'Calendar'}  {$APP.Event} @@ -28,17 +28,21 @@ {if $MODULE eq 'Leads'} - - - - + + + + + + + + - + {else} diff --git a/Smarty/templates/modules/PickList/PickList.tpl b/Smarty/templates/modules/PickList/PickList.tpl index f8dd235..62f16f4 100644 --- a/Smarty/templates/modules/PickList/PickList.tpl +++ b/Smarty/templates/modules/PickList/PickList.tpl @@ -46,9 +46,7 @@ - +
#{$MOD.FieldLabel}{$MOD.FieldType}
{$MOD.LBL_MAPPING_OTHER_MODULES}
#{$MOD.FieldLabel}{$MOD.FieldType}
{$MOD.LBL_MAPPING_OTHER_MODULES}
{$MOD.LBL_CURRENCY_TOOL}
{$APP.Accounts} {$APP.Contacts} {$APP.Potentials}{$MOD.LBL_CURRENCY_TOOL}
{$MOD.LBL_USERS}{$MOD.VTLIB_LBL_MODULE_MANAGER} > {$MODULE} > {'LBL_FIELD_SETTINGS'|@getTranslatedString:$MODULE}{$MOD.VTLIB_LBL_MODULE_MANAGER} > {$MODULE|@getTranslatedString:$MODULE} > {'LBL_FIELD_SETTINGS'|@getTranslatedString:$MODULE}
diff --git a/config.help.link.php b/config.help.link.php index 44fc0ed..853ff67 100644 --- a/config.help.link.php +++ b/config.help.link.php @@ -8,8 +8,8 @@ * All Rights Reserved. *************************************************************************************/ -$helpLinks = array( - 'WORKFLOW_TRIGGER_TYPES' => 'http://wiki.vtiger.com/index.php/Vtiger530:Module_Workflow', -); +define('WORKFLOW_TRIGGER_TYPES','http://wiki.vtiger.com/index.php/Vtiger530:Module_Workflow'); +define('BASE_HELP_WIKI','http://wiki.vtiger.com'); +define('MAIN_HELP_PAGE','http://wiki.vtiger.com/index.php/Main_Page'); ?> diff --git a/config.template.php b/config.template.php index 1446fda..91ac7fc 100644 --- a/config.template.php +++ b/config.template.php @@ -27,10 +27,10 @@ $CALCULATOR_DISPLAY = 'true'; $CHAT_DISPLAY = 'true'; $USE_RTE = 'true'; -// url for customer portal (Example: http://vtiger.com/portal) -$PORTAL_URL = 'http://vtiger.com/customerportal'; +// url for customer portal (Example: http://your_support_domain.tld/portal) +$PORTAL_URL = 'http://your_support_domain.tld/customerportal'; -// helpdesk support email id and support name (Example: 'support@vtiger.com' and 'vtiger support') +// helpdesk support email id and support name (Example: 'support@your_support_domain.tld' and 'your-support name') $HELPDESK_SUPPORT_EMAIL_ID = '_USER_SUPPORT_EMAIL_'; $HELPDESK_SUPPORT_NAME = 'your-support name'; $HELPDESK_SUPPORT_EMAIL_REPLY_ID = $HELPDESK_SUPPORT_EMAIL_ID; @@ -200,4 +200,7 @@ if(isset($default_timezone) && function_exists('date_default_timezone_set')) { /** minimum cron frequency -- In minutes */ $MINIMUM_CRON_FREQUENCY = 15; +// Override with developer settings +@include('config-dev.inc.php'); + ?> \ No newline at end of file diff --git a/copyright.html b/copyright.html index 2c2aa51..bb5b252 100644 --- a/copyright.html +++ b/copyright.html @@ -1,27 +1,224 @@ + - - Copyright - + +coreBOS Licence and Copyright + + - - -
This software is a collective work consisting of the following major Open Source components:
-Apache software, MySQL server, PHP, SugarCRM, ADOdb, Smarty, PHPMailer, phpSysinfo, MagpieRSS and others, each licensed under a separate Open Source License. -vtiger.com is not affiliated with nor endorsed by any of the above providers. See Copyrights for details.);
+
+

coreBOS Licence and Copyright

+This software is a collective work consisting of various Open Source components like:
+Apache software, MySQL server, PHP, vtiger CRM, ADOdb, Smarty, JQuery, PHPMailer, MagpieRSS, just to mention a few, each Licenced under a separate Open Source Licence. +neither coreBOS nor TSolucio (the company behind coreBOS) are affiliated with nor endorsed by any of the above providers.
+
+In general the whole application is Licenced under the Vtiger Public Licence (VPL), which is an adaption of Mozilla Public Licence. Where this may produce conflicts with third party libraries used, each library will maintain their own Licence. If any licensing conflicts are detected and require our action please contact us at corebos@tsolucio.com and we will attend at the shortest possible . +
+At the application's root directory you will find the complete contents of the VPL Licence in the file licenceAgreement.html
+
+The full licence can be read next:
+ +

Vtiger Public Licence

+
+
+The vtiger Public License Version 1.1 is based on the Mozilla Public License Version 1.1 +
+vtiger Public License +Version 1.1 +

+Copyright (c) 2004-2005 www.vtiger.com All rights reserved. +

+PLEASE READ THE FOLLOWING LICENSE AGREEMENT CAREFULLY. ANY USE OF SOFTWARE DOWNLOADED OR ORDERED FROM VTIGER IS PERMITTED ONLY UNDER LICENSE WITH VTIGER. BY DOWNLOADING THIS SOFTWARE YOU AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE AGREEMENT. +
    +
  1. Definitions. +
    +
    1.0. "Commercial Use" means distribution or otherwise making the Covered Code available to a third party. + +

    1.1. ''Contributor'' means each entity that creates or contributes to the creation of Modifications. + +

    1.2. ''Contributor Version'' means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor. + +

    1.3. ''Covered Code'' means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof. + +

    1.4. ''Electronic Distribution Mechanism'' means a mechanism generally accepted in the software development community for the electronic transfer of data. + +

    1.5. ''Executable'' means Covered Code in any form other than Source Code. + +

    1.6. ''Initial Developer'' means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A. + +

    1.7. ''Larger Work'' means a work which combines Covered Code or portions thereof with code not governed by the terms of this License. + +

    1.8. ''License'' means this document. +
    +
    1.8.1. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein. +
    +

    1.9. ''Modifications'' means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is: +
    +
    A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
    + +
    B. Any new file that contains any part of the Original Code or previous Modifications.
    +
    +

    1.10. ''Original Code'' means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License. + +

    1.10.1. "Patent Claims" means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor. + +

    1.11. ''Source Code'' means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor's choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge. + +

    1.12. "You'' (or "Your") means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, "You'' includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, "control'' means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. +

    +
  2. +Source Code License. +
    +
    +
    2.1.The Initial Developer Grant.
    + The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims: +
    +
    (a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and +
    (b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof). +
    (c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License. - - +
    (d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices. +
    +

    2.2. Contributor Grant. + Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license +
    +
    (a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and + +
    (b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination). + +
    (c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code. + +
    (d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor. +
    +

    +
  3. +Distribution Obligations. +
    +
    3.1. Application of License. + The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients' rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5. + +

    3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party. + +

    3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code. + +

    3.4. Intellectual Property Matters +
    +
    (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled "LEGAL'' which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained. + +
    (b)Contributor APIs. + If Contributor's Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file. + +
    (c)Representations. + Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor's Modifications are Contributor's original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License. +
    +
    + +

    3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients' rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer. + +

    3.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients' rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient's rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or any Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer. + +

    3.7. Larger Works. + You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code. +

    +
  4. +Inability to Comply Due to Statute or Regulation. +
    +
    If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. +

    +
  5. +Application of this License. +
    +This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code. +

    +
  6. +Versions of the License. +
    +
    6.1. New Versions. + vtiger may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number. + +

    6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by vtiger. No one other than vtiger has the right to modify the terms applicable to Covered Code created under this License. + +

    6.3. Derivative Works. + If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases ''vtiger'or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the vtiger Public License. (Filling in the name of the Initial Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.) +

    +
  7. +DISCLAIMER OF WARRANTY. +
    +COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS'' BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. +

    +
  8. +TERMINATION. + +
    + 8.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive. + +

    8.2. If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You file such action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above. + + (b) any software, hardware, or device, other than such Participant's Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant. + +

    8.3. If You assert a patent infringement claim against Participant alleging that such Participant's Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license. + +

    8.4. In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination. +

    +
  9. +LIMITATION OF LIABILITY. +
    + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. +

    +
  10. +U.S. GOVERNMENT END USERS. +
    +The Covered Code is a ''commercial item,'' as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of ''commercial computer software'' and ''commercial computer software documentation,'' as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein. +

    +
  11. +MISCELLANEOUS. +
    + This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by Indian laws (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in India, any litigation relating to this License shall be subject to the jurisdiction of the Courts in Chennai, with venue lying in Tamil Nadu State, India, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys' fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. +

    +
  12. +RESPONSIBILITY FOR CLAIMS. +
    + As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability. +

    +
  13. +MULTIPLE-LICENSED CODE. +
    + Initial Developer may designate portions of the Covered Code as "Multiple-Licensed". "Multiple-Licensed" means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the MPL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A. +

    +
  14. +
+ +EXHIBIT A -vtiger Public License. +

+"The contents of this file are subject to the vtiger Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License." +

+Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. +

+The Original Code is vtiger Outlook Plug-in. +

+The Initial Developer of the Original Code is vtiger. Portions created by vtiger are Copyright (C) www.vtiger.com. All Rights Reserved. +

+Contributor(s): ______________________________________. +

+ [NOTE: The text of this Exhibit A may differ slightly from the text of the notices in the Source Code files of the Original Code. You should use the text of this Exhibit A rather than the text found in the Original Code Source Code for Your Modifications.] + +

+
+ + diff --git a/cron/send_mail.php b/cron/send_mail.php index f817ac8..2326308 100755 --- a/cron/send_mail.php +++ b/cron/send_mail.php @@ -51,7 +51,7 @@ function sendmail($to,$from,$subject,$contents,$mail_server,$mail_server_usernam $mail->IsHTML(true); // set email format to HTML $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; - $mail->Sender= getReturnPath($mail->Host); + $mail->Sender= getReturnPath($mail->Host, $mail->From); if(!$mail->Send()) { echo "Message could not be sent.

"; diff --git a/data/CRMEntity.php b/data/CRMEntity.php index 614d00b..0407139 100644 --- a/data/CRMEntity.php +++ b/data/CRMEntity.php @@ -2012,8 +2012,10 @@ class CRMEntity { $condvalue = $table_name . "." . $column_name; $condition = "$pritablename.$secfieldname=$condvalue"; } - $secQuery = "select $table_name.* from $table_name inner join vtiger_crmentity on " . - "vtiger_crmentity.crmid=$table_name.$column_name and vtiger_crmentity.deleted=0"; + //$secQuery = "select $table_name.* from $table_name inner join vtiger_crmentity on " . + // "vtiger_crmentity.crmid=$table_name.$column_name and vtiger_crmentity.deleted=0"; + $secQuery2 = "inner join vtiger_crmentity as crmentity$table_name on " . + "crmentity$table_name.crmid=$table_name.$column_name and crmentity$table_name.deleted=0"; $query = ''; if ($pritablename == 'vtiger_crmentityrel') { $condition = "($table_name.$column_name={$tmpname}.{$secfieldname} " . @@ -2033,7 +2035,10 @@ class CRMEntity { } - $query .= " left join ($secQuery) as $table_name on {$condition}"; + //$query .= " left join ($secQuery) as $table_name on {$condition}"; + //performance improvement, this should be equivalent to the subquery but masses faster + $query .= " left join $table_name on {$condition}"; + $query .= " $secQuery2"; return $query; } @@ -2433,6 +2438,7 @@ class CRMEntity { * return array $list_buttons - for module (eg: 'Accounts') */ function getListButtons($app_strings) { + global $currentModule; $list_buttons = Array(); if (isPermitted($currentModule, 'Delete', '') == 'yes') diff --git a/include/CustomFieldUtil.php b/include/CustomFieldUtil.php index e220bd4..d75bfd8 100644 --- a/include/CustomFieldUtil.php +++ b/include/CustomFieldUtil.php @@ -256,7 +256,7 @@ function getCalendarCustomFields($tabid,$mode='edit',$col_fields='') { if ($mode == 'edit') { $custquery .= " AND vtiger_profile2field.readonly = 0"; } - $custquery .= " ORDER BY vtiger_field.fieldid"; + $custquery .= " GROUP BY vtiger_field.fieldid"; array_push($custparams, $profileList); } $custresult = $adb->pquery($custquery, $custparams); @@ -272,6 +272,10 @@ function getCalendarCustomFields($tabid,$mode='edit',$col_fields='') { $maxlength = $adb->query_result($custresult,$i,"maximumlength"); $generatedtype = $adb->query_result($custresult,$i,"generatedtype"); $typeofdata = $adb->query_result($custresult,$i,"typeofdata"); + $defaultvalue = $adb->query_result($custresult,$i,"defaultvalue"); + if(empty($col_fields[$fieldname])) { + $col_fields[$fieldname] = $defaultvalue; + } if ($mode == 'edit') $custfld = getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype,'Calendar',$mode, $typeofdata); diff --git a/include/ListView/ListViewController.php b/include/ListView/ListViewController.php index 2eea4bd..94cb25a 100644 --- a/include/ListView/ListViewController.php +++ b/include/ListView/ListViewController.php @@ -443,11 +443,13 @@ class ListViewController { } } elseif ( in_array($uitype,array(7,9,90)) ) { $value = "".textlength_check($value)."

"; + } elseif ($field->getUIType() == 55) { + $value = getTranslatedString($value,$currentModule); } else { $value = textlength_check($value); } - $parenttab = getParentTab(); + $parenttab = getParentTab(); $nameFields = $this->queryGenerator->getModuleNameFields($module); $nameFieldList = explode(',',$nameFields); if(in_array($fieldName, $nameFieldList) && $module != 'Emails' ) { diff --git a/include/ListView/RelatedListViewContents.php b/include/ListView/RelatedListViewContents.php index e8d3a8d..0ce5456 100644 --- a/include/ListView/RelatedListViewContents.php +++ b/include/ListView/RelatedListViewContents.php @@ -46,8 +46,8 @@ if($ajaxaction == "LOADRELATEDLIST") { !$resetCookie) { //TODO for 5.3 this should be COOKIE not REQUEST, change here else where // this logic is used for listview checkbox selection propogation. - $checkedRecordIdString = $_REQUEST[$relatedModule.'_all']; - $checkedRecordIdString = rtrim($checkedRecordIdString); + $checkedRecordIdString = (empty($_REQUEST[$relatedModule.'_all']) ? $_COOKIE[$relatedModule.'_all'] : $_REQUEST[$relatedModule.'_all']); + $checkedRecordIdString = rtrim($checkedRecordIdString,';'); $checkedRecordIdList = explode(';', $checkedRecordIdString); $relatedListData["checked"]=array(); if (isset($relatedListData['entries'])) { diff --git a/include/QueryGenerator/QueryGenerator.php b/include/QueryGenerator/QueryGenerator.php index f8ae71b..ce4b863 100644 --- a/include/QueryGenerator/QueryGenerator.php +++ b/include/QueryGenerator/QueryGenerator.php @@ -449,10 +449,12 @@ class QueryGenerator { $tableJoinMapping['vtiger_attachmentsfolder'] = 'INNER JOIN'; } + $alias_count=2; foreach ($tableJoinCondition as $fieldName=>$conditionInfo) { foreach ($conditionInfo as $tableName=>$condition) { if(!empty($tableList[$tableName])) { - $tableNameAlias = $tableName.'2'; + $tableNameAlias = $tableName.$alias_count; + $alias_count++; $condition = str_replace($tableName, $tableNameAlias, $condition); } else { $tableNameAlias = ''; diff --git a/include/Webservices/AuthToken.php b/include/Webservices/AuthToken.php index 7779348..6786e01 100644 --- a/include/Webservices/AuthToken.php +++ b/include/Webservices/AuthToken.php @@ -14,6 +14,10 @@ $user = new Users(); $userid = $user->retrieve_user_id($username); + if (empty($userid)) { + throw new WebServiceException(WebServiceErrorCode::$AUTHREQUIRED,'Given user cannot be found'); + } + $authToken = uniqid(); $servertime = time(); diff --git a/include/Webservices/DeleteUser.php b/include/Webservices/DeleteUser.php index c19378b..ab74b5a 100644 --- a/include/Webservices/DeleteUser.php +++ b/include/Webservices/DeleteUser.php @@ -25,7 +25,7 @@ function vtws_deleteUser($id, $newOwnerId,$user){ $meta = $handler->getMeta(); $entityName = $meta->getObjectEntityName($id); - $types = vtws_listtypes($user); + $types = vtws_listtypes(null, $user); if(!in_array($entityName,$types['types'])){ throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED, "Permission to perform the operation is denied, EntityName = ".$entityName); diff --git a/include/Webservices/GetUpdates.php b/include/Webservices/GetUpdates.php index 0577af3..b5423c7 100644 --- a/include/Webservices/GetUpdates.php +++ b/include/Webservices/GetUpdates.php @@ -11,7 +11,7 @@ require_once 'include/Webservices/Utils.php'; require_once 'include/Webservices/ModuleTypes.php'; require_once 'include/utils/CommonUtils.php'; - function vtws_sync($mtime,$elementType,$syncType,$user){ + function vtws_sync($mtime,$elementType,$syncType='',$user=''){ global $adb, $recordString,$modifiedTimeString; $numRecordsLimit = 100; diff --git a/include/Webservices/Login.php b/include/Webservices/Login.php index dd20363..5856fcb 100644 --- a/include/Webservices/Login.php +++ b/include/Webservices/Login.php @@ -13,6 +13,9 @@ $user = new Users(); $userId = $user->retrieve_user_id($username); + if (empty($userId)) { + throw new WebServiceException(WebServiceErrorCode::$AUTHREQUIRED,'Given user cannot be found'); + } $token = vtws_getActiveToken($userId); if($token == null){ throw new WebServiceException(WebServiceErrorCode::$INVALIDTOKEN,"Specified token is invalid or expired"); diff --git a/include/fields/CurrencyField.php b/include/fields/CurrencyField.php index e2fcaf5..8a60ef1 100644 --- a/include/fields/CurrencyField.php +++ b/include/fields/CurrencyField.php @@ -197,6 +197,8 @@ class CurrencyField { $number = str_replace('.', $decimalSeparator, $value); return $number; } + $negativeNumber=($value<0); + $value=abs($value); if($currencyPattern == $this->CURRENCY_PATTERN_SINGLE_GROUPING) { // Separate the numeric and decimal parts $numericParts = explode('.', $value); @@ -215,6 +217,7 @@ class CurrencyField { } // Re-create the currency value combining the whole number and the decimal part using Decimal separator $number = implode($decimalSeparator, $numericParts); + if ($negativeNumber) $number='-'.$number; return $number; } if($currencyPattern == $this->CURRENCY_PATTERN_THOUSAND_GROUPING) { @@ -239,6 +242,7 @@ class CurrencyField { } // Re-create the currency value combining the whole number and the decimal part using Decimal separator $number = implode($decimalSeparator, $numericParts); + if ($negativeNumber) $number='-'.$number; return $number; } if($currencyPattern == $this->CURRENCY_PATTERN_MIXED_GROUPING) { @@ -275,6 +279,7 @@ class CurrencyField { } // Re-create the currency value combining the whole number and the decimal part using Decimal separator $number = implode($decimalSeparator, $numericParts); + if ($negativeNumber) $number='-'.$number; return $number; } return $number; diff --git a/include/install/language/en_us.lang.php b/include/install/language/en_us.lang.php index f06fff7..101eb7e 100644 --- a/include/install/language/en_us.lang.php +++ b/include/install/language/en_us.lang.php @@ -26,16 +26,16 @@ $optionalModuleStrings = array( ); $installationStrings = array( - 'LBL_VTIGER_CRM_5' => 'vtiger CRM 5', + 'APP_NAME' => 'coreBOS', 'LBL_CONFIG_WIZARD' => 'Configuration Wizard', 'LBL_WELCOME' => 'Welcome', 'LBL_WELCOME_CONFIG_WIZARD' => 'Welcome to Configuration Wizard', - 'LBL_ABOUT_CONFIG_WIZARD' => 'This configuration wizard helps you install vtigerCRM ', - 'LBL_ABOUT_VTIGER' => 'vtiger CRM is a community-driven, fully open source, CRM software project.

- The aim of the project is to provide the best and most open CRM solution with the lowest total cost of ownership to small and medium enterprises.

- The product is widely used throughout the world, with over a thousand downloads a day.

- vtiger CRM has an active community of developers and users, with contributors from many different countries.

- It is available in many languages, with a strong partner network in dozens of countries.', + 'LBL_ABOUT_CONFIG_WIZARD' => 'This configuration wizard helps you install coreBOS ', + 'LBL_ABOUT_VTIGER' => 'coreBOS is a community-driven, fully open source, Business empowering software project.

+ The aim of the project is to provide a powerful software environment for your company to grow upon with the lowest total cost of ownership for small and medium enterprises.

+ The product is widely used throughout the world.

+ coreBOS has an active community of developers and users, with contributors from many different countries.

+ It is available in many languages.', 'LBL_INSTALL' => 'Install', 'LBL_MIGRATE' => 'Migrate', 'ERR_RESTRICTED_FILE_ACCESS' => 'Sorry! Attempt to access restricted file', @@ -57,7 +57,7 @@ $installationStrings = array( 'MSG_CONFIG_FILE_CREATED' => 'Configuration file (config.inc.php) was successfully created', 'LBL_FINISH' => 'Finish', 'LBL_CONFIG_COMPLETED' => 'Configuration Completed', - 'LBL_PHP_VERSION_GT_5' => 'PHP version >= 5.2', + 'LBL_PHP_VERSION_GT_5' => 'PHP version >= 5.3', 'LBL_YES' => 'Yes', 'LBL_NO' => 'No', 'LBL_NOT_CONFIGURED' => 'Not Configured', @@ -72,7 +72,7 @@ $installationStrings = array( 'LBL_NOT_RECOMMENDED' => 'Not Recommended', 'LBL_PHP_DIRECTIVES_HAVE_RECOMMENDED_VALUES' => 'Your PHP directives have the Recommended values', 'MSG_PROVIDE_READ_WRITE_ACCESS_TO_PROCEED' => 'Provide Read/Write access to the files and directories listed to Proceed', - 'WARNING_PHP_DIRECTIVES_NOT_RECOMMENDED_STILL_WANT_TO_PROCEED' => 'Some of the PHP Settings do not meet the recommended values. This might affect some of the features of vtiger CRM. Are you sure, you want to proceed?', + 'WARNING_PHP_DIRECTIVES_NOT_RECOMMENDED_STILL_WANT_TO_PROCEED' => 'Some of the PHP Settings do not meet the recommended values. This might affect some of the features of coreBOS. Are you sure, you want to proceed?', 'LBL_CHANGE' => 'Change', 'LBL_DATABASE_INFORMATION' => 'Database Information', 'LBL_CRM_CONFIGURATION' => 'CRM Configuration', @@ -98,7 +98,7 @@ $installationStrings = array( 'LBL_MISSING_REQUIRED_FIELDS' => 'Missing required fields', 'ERR_ADMIN_EMAIL_INVALID' => 'The email id in the admin email field is invalid', 'ERR_STANDARDUSER_EMAIL_INVALID' => 'The email id in the standard user email field is invalid', - 'WARNING_LOCALHOST_IN_SITE_URL' => 'Specify the exact host name instead of \"localhost\" in Site URL field, otherwise you will experience some issues while working with vtiger plug-ins. Do you wish to Continue?', + 'WARNING_LOCALHOST_IN_SITE_URL' => 'Specify the exact host name instead of \"localhost\" in Site URL field, otherwise you will experience some issues while working with coreBOS plug-ins. Do you wish to Continue?', 'LBL_DATABASE_CONFIGURATION' => 'Database Configuration', 'LBL_ENABLED' => 'Enabled', 'LBL_NOT_ENABLED' => 'Not Enabled', @@ -127,16 +127,15 @@ $installationStrings = array( 'LBL_LOGIN_USING_ADMIN' => 'Please log in using the "admin" user name and the password you entered in step 3/4', 'LBL_SET_OUTGOING_EMAIL_SERVER' => 'Do not forget to set the outgoing email server (setup accessible from Settings->Outgoing Server)', 'LBL_RENAME_HTACCESS_FILE' => 'Rename htaccess.txt file to .htaccess to control public file access', - 'MSG_HTACCESS_DETAILS' => 'This .htaccess file will work if "AllowOverride All" is set on Apache server configuration file (httpd.conf) for the DocumentRoot or for the current vtiger path.
+ 'MSG_HTACCESS_DETAILS' => 'This .htaccess file will work if "AllowOverride All" is set on Apache server configuration file (httpd.conf) for the DocumentRoot or for the current coreBOS path.
If this AllowOverride is set as None ie., "AllowOverride None" then .htaccess file will not take into effect.
If AllowOverride is None then add the following configuration in the apache server configuration file (httpd.conf)
- <Directory "C:/Program Files/vtigercrm/apache/htdocs/vtigerCRM">
Options -Indexes
</Directory>

+ <Directory "C:/Program Files/corebos/apache/htdocs/coreBOS">
Options -Indexes
</Directory>

So that without .htaccess file we can restrict the directory listing', 'LBL_YOU_ARE_IMPORTANT' => 'You are very important to us!', 'LBL_PRIDE_BEING_ASSOCIATED' => 'We take pride in being associated with you', - 'LBL_TALK_TO_US_AT_FORUMS' => 'Talk to us at forums', - 'LBL_DISCUSS_WITH_US_AT_BLOGS' => 'Discuss with us at blogs', - 'LBL_WE_AIM_TO_BE_BEST' => 'We aim to be - simply the best', + 'LBL_TALK_TO_US_AT_FORUMS' => 'Talk to us in our Google+ Community or LinkedIn Group', + 'LBL_WE_AIM_TO_BE_BEST' => 'We aim to help you do your business', 'LBL_SPACE_FOR_YOU' => 'Come on over, there is space for you too!', 'LBL_NO_OPTIONAL_MODULES_FOUND' => 'No Optional Modules found', 'LBL_PREVIOUS_INSTALLATION_INFORMATION' => 'Previous Installation Information', @@ -169,7 +168,7 @@ $installationStrings = array( 'LBL_DATABASE_CHECK' => 'Database Check', 'MSG_TABLES_IN_INNODB' => 'Required tables were detected to be in proper Engine type (InnoDB)', 'MSG_CLOSE_WINDOW_TO_PROCEED' => 'You can close this window and proceed further with migration', - 'LBL_RECOMMENDATION_FOR_PROPERLY_WORKING_CRM' => 'For proper functionality of vtiger CRM, we recommend the following', + 'LBL_RECOMMENDATION_FOR_PROPERLY_WORKING_CRM' => 'For proper functionality of coreBOS, we recommend the following', 'LBL_TABLES_SHOULD_BE_INNODB' => 'Tables to have InnoDB engine type', 'QUESTION_WHAT_IS_INNODB' => 'What is InnoDB', 'LBL_TABLES_CHARSET_TO_BE_UTF8' => 'To get complete UTF-8 support, tables should have default charset UTF8', @@ -207,7 +206,7 @@ $installationStrings = array( 'MSG_DATABASE_COPY_SUCCEDED' => 'Database copy was successfully created.
Click Next » to proceed', 'MSG_SUCCESSFULLY_FIXED_TABLE_TYPES' => 'Successfully changed tables to InnoDB engine', 'LBL_MIGRATION' => 'Migration', - 'LBL_SOURCE_VERSION_NOT_SET' => 'Source Version is not set. Please check vtigerversion.php and continue the Patch Process', + 'LBL_SOURCE_VERSION_NOT_SET' => 'Source Version is not set. Please check corebosversion.php and continue the Patch Process', 'LBL_GOING_TO_APPLY_DB_CHANGES' => 'Going to apply the Database Changes', 'LBL_DATABASE_CHANGES' => 'Database changes', 'LBL_STARTS' => 'Starts', diff --git a/include/install/resources/utils.php b/include/install/resources/utils.php index d12b3c0..70fe4cb 100644 --- a/include/install/resources/utils.php +++ b/include/install/resources/utils.php @@ -779,10 +779,10 @@ ini_set('memory_limit','64M'); \$CHAT_DISPLAY = 'true'; \$USE_RTE = 'true'; -// url for customer portal (Example: http://vtiger.com/portal) -\$PORTAL_URL = 'http://vtiger.com/customerportal'; +// url for customer portal (Example: http://your_support_domain.tld/portal) +\$PORTAL_URL = 'http://your_support_domain.tld/customerportal'; -// helpdesk support email id and support name (Example: 'support@vtiger.com' and 'vtiger support') +// helpdesk support email id and support name (Example: 'support@your_support_domain.tld' and 'your-support name') \$HELPDESK_SUPPORT_EMAIL_ID = '{$this->adminEmail}'; \$HELPDESK_SUPPORT_NAME = 'your-support name'; \$HELPDESK_SUPPORT_EMAIL_REPLY_ID = \$HELPDESK_SUPPORT_EMAIL_ID; diff --git a/include/js/Inventory.js b/include/js/Inventory.js index becc268..2836c99 100644 --- a/include/js/Inventory.js +++ b/include/js/Inventory.js @@ -338,8 +338,8 @@ function validateInventory(module) if (!emptyCheck("productName"+i,alert_arr.LINE_ITEM,"text")) return false if (!emptyCheck("qty"+i,"Qty","text")) return false - if (!numValidate("qty"+i,"Qty","any")) return false - if (!numConstComp("qty"+i,"Qty","G","0")) return false + if (!numValidate("qty"+i,"Qty","any",true)) return false + //if (!numConstComp("qty"+i,"Qty","G","0")) return false if (!emptyCheck("listPrice"+i,alert_arr.LIST_PRICE,"text")) return false if (!numValidate("listPrice"+i,alert_arr.LIST_PRICE,"any")) return false } @@ -747,7 +747,7 @@ function setDiscount(currObj,curr_row) var discount_checks = new Array(); discount_checks = document.getElementsByName("discount"+curr_row); - + calcProductTotal(curr_row); if(discount_checks[0].checked == true) { document.getElementById("discount_type"+curr_row).value = 'zero'; diff --git a/include/js/ListView.js b/include/js/ListView.js index 20ea717..20fa615 100644 --- a/include/js/ListView.js +++ b/include/js/ListView.js @@ -105,6 +105,19 @@ function mass_edit_formload(idstring,module,parenttab) { var excludedRecords=document.getElementById("excludedRecords").value; var viewid =getviewId(); $("status").style.display="inline"; + var urlstring = ''; + var searchtype = document.basicSearch.searchtype.value; + if(document.basicSearch.searchtype.searchlaunched != undefined && document.basicSearch.searchtype.searchlaunched=='basic') { + search_fld_val= $('bas_searchfield').options[$('bas_searchfield').selectedIndex].value; + search_txt_val= encodeURIComponent(document.basicSearch.search_text.value); + if (search_txt_val!='') { // if the search fields are not empty + urlstring = '&query=true&ajax=true&search=true&search_field='+search_fld_val+'&searchtype=BasicSearch&search_text='+search_txt_val; + } + } else if(document.basicSearch.searchtype.searchlaunched != undefined && document.basicSearch.searchtype.searchlaunched=='advance' && checkAdvancedFilter()) { + var advft_criteria = $('advft_criteria').value; + var advft_criteria_groups = $('advft_criteria_groups').value; + urlstring = '&query=true&ajax=true&search=true&advft_criteria='+advft_criteria+'&advft_criteria_groups='+advft_criteria_groups+'&searchtype=advance'; + } new Ajax.Request( 'index.php', { @@ -113,7 +126,7 @@ function mass_edit_formload(idstring,module,parenttab) { scope: 'command' }, method: 'post', - postBody:"module="+encodeURIComponent(module)+"&action="+encodeURIComponent(module+'Ajax')+"&parenttab="+encodeURIComponent(parenttab)+"&file=MassEdit&mode=ajax&idstring="+idstring+"&viewname="+viewid+"&excludedRecords="+excludedRecords, + postBody:"module="+encodeURIComponent(module)+"&action="+encodeURIComponent(module+'Ajax')+"&parenttab="+encodeURIComponent(parenttab)+"&file=MassEdit&mode=ajax&idstring="+idstring+"&viewname="+viewid+"&excludedRecords="+excludedRecords+urlstring, onComplete: function(response) { $("status").style.display="none"; var result = response.responseText; diff --git a/include/js/dtlviewajax.js b/include/js/dtlviewajax.js index 283bbe4..1ec96a9 100644 --- a/include/js/dtlviewajax.js +++ b/include/js/dtlviewajax.js @@ -452,7 +452,7 @@ function dtlViewAjaxSave(fieldLabel,module,uitype,tableName,fieldName,crmId) desc = desc.replace(/(^|[\n ])((www|ftp)\.[\w\-]+\.[\w\-.\~]+(?:\/[^ \"\t\n\r<]*)?)/g, "$1$2"); desc = desc.replace(/(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)/i, "$1$2@$3"); desc = desc.replace(/,\"|\.\"|\)\"|\)\.\"|\.\)\"/, "\""); - desc = desc.replace(/[\n\r]+/g, "
 "); + desc = desc.replace(/[\n\r]/g, "
 "); getObj(dtlView).innerHTML = desc; } else diff --git a/include/js/general.js b/include/js/general.js index 095e10d..d79cc33 100755 --- a/include/js/general.js +++ b/include/js/general.js @@ -226,8 +226,8 @@ function emptyCheck(fldName,fldLabel, fldType) { return true } }else if((fldType == "textarea") - && (typeof(CKEDITOR)!=='undefined' && CKEDITOR.intances[fldName] !== 'undefined')) { - var textObj = CKEDITOR.intances[fldName]; + && (typeof(CKEDITOR)!=='undefined' && CKEDITOR.instances[fldName] !== 'undefined')) { + var textObj = CKEDITOR.instances[fldName]; // thank you Stefan (from developers list) var textValue = textObj.getData(); if (trim(textValue) == '' || trim(textValue) == '
') { alert(fldLabel+alert_arr.CANNOT_BE_NONE); @@ -254,7 +254,7 @@ function patternValidate(fldName,fldLabel,type) { /*changes made to fix -- ticket#3278 & ticket#3461 var re=new RegExp(/^.+@.+\..+$/)*/ //Changes made to fix tickets #4633, #5111 to accomodate all possible email formats - var re=new RegExp(/^[a-zA-Z0-9]+([!"#$%&'()*+,./:;<=>?@\^_`{|}~-]?[a-zA-Z0-9])*@[a-zA-Z0-9]+([\_\-\.]?[a-zA-Z0-9]+)*\.([\-\_]?[a-zA-Z0-9])+(\.?[a-zA-Z0-9]+)?$/); + var re=new RegExp(/^[a-zA-Z0-9]+([!"#$%&'()*+,./:;<=>?@\^_`{|}~-]?[a-zA-Z0-9]+[\_\-]?)*@[a-zA-Z0-9]+([\_\-\.]?[a-zA-Z0-9]+)*\.([\-\_]?[a-zA-Z0-9])+(\.?[a-zA-Z0-9]+)?$/); } if (type.toUpperCase()=="DATE") {//DATE validation @@ -1977,7 +1977,7 @@ function ReplyCompose(id,mode) openPopUp('xComposeEmail',this,url,'createemailWin',820,689,'menubar=no,toolbar=no,location=no,status=no,resizable=no,scrollbars=yes'); } -function OpenCompose(id,mode) +function OpenCompose(id,mode,crmid) { switch(mode) { @@ -1991,16 +1991,16 @@ function OpenCompose(id,mode) url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&record='+id+'&forward=true'; break; case 'Invoice': - url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf'; + url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf&invmodid='+crmid; break; case 'PurchaseOrder': - url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf'; + url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf&invmodid='+crmid; break; case 'SalesOrder': - url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf'; + url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf&invmodid='+crmid; break; case 'Quote': - url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf'; + url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+mode+'_'+id+'.pdf&invmodid='+crmid; break; case 'Documents': url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&attachment='+id+''; @@ -2206,7 +2206,7 @@ function fnDropDown(obj,Lay){ } else tagName.style.left= leftSide + 'px'; - tagName.style.top= topSide + 28 +'px'; + tagName.style.top= topSide + 22 +'px'; tagName.style.display = 'block'; } diff --git a/include/js/popup.js b/include/js/popup.js deleted file mode 100644 index 3711704..0000000 --- a/include/js/popup.js +++ /dev/null @@ -1,20 +0,0 @@ -/********************************************************************************* - ** The contents of this file are subject to the vtiger CRM Public License Version 1.0 - * ("License"); You may not use this file except in compliance with the License - * The Original Code is: vtiger CRM Open Source - * The Initial Developer of the Original Code is vtiger. - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * - ********************************************************************************/ - -function mypopup() -{ - mywindow = window.open("copyright.html","mywindow", "height=115, width=575"); - mywindow.moveTo(210,620); -} - -function newpopup(str){ - window.open (str,"mywinw","menubar=1,resizable=1,scrollbars=yes"); -// window.parent.close(); -} diff --git a/include/language/en_us.lang.php b/include/language/en_us.lang.php index 898ff7d..43bf960 100644 --- a/include/language/en_us.lang.php +++ b/include/language/en_us.lang.php @@ -20,7 +20,8 @@ * Contributor(s): ______________________________________.. ********************************************************************************/ $app_strings = array ( -'LBL_BROWSER_TITLE' => 'vtiger CRM 5 - Commercial Open Source CRM', +'LBL_BROWSER_TITLE' => 'coreBOS', +'APP_NAME' => 'coreBOS', 'LBL_MY_ACCOUNT' => 'My Organization', 'LBL_MY_PREFERENCES' => 'My Preferences', 'LBL_ADMIN' => 'Admin', @@ -34,8 +35,8 @@ $app_strings = array ( 'all'=>'All', 'LBL_UPCOMING_EVENTS'=>'Upcoming Activities', 'LBL_PENDING_EVENTS'=>'Pending Activities', -'NTC_WELCOME_MESSAGE' => 'Welcome to vtiger CRM!', -'NTC_DESCRIPTION' => 'Use a valid username and password to login to the vtiger CRM.', +'NTC_WELCOME_MESSAGE' => 'Welcome to coreBOS!', +'NTC_DESCRIPTION' => 'Use a valid username and password to login to the coreBOS.', 'NTC_WELCOME' => 'Welcome', 'NTC_NO_ITEMS_DISPLAY' => 'none', 'LBL_OR' => 'or', @@ -140,7 +141,7 @@ $app_strings = array ( 'LBL_LIST_OF' => 'of', 'LNK_PRINT' => 'Print', 'LNK_HELP' => 'Help', -'LNK_VTDOCS' => 'vtiger Docs', +'LNK_VTDOCS' => 'coreBOS Docs', 'LNK_ABOUT' => 'About', 'LNK_OUTLOOK' => './include/images/outlook_download.gif', 'SINGLE_Accounts' => 'Organization', @@ -217,6 +218,7 @@ $app_strings = array ( 'NTC_MERGE_CONFIRMATION' => 'Are you sure you want to merge this record?', 'LBL_MERGE_BUTTON_TITLE' => 'Merge', 'LBL_MERGE_BUTTON_KEY' => 'Merge', +'DownloadMergeFile'=>'Download merged document', 'LBL_SELECTEMAILTEMPLATE_BUTTON_TITLE' => 'Select Email Template', 'LBL_SELECTEMAILTEMPLATE_BUTTON_KEY' => 'Select Email Template', 'LBL_SELECTEMAILTEMPLATE_BUTTON_LABEL' => 'Select Email Template', @@ -602,7 +604,6 @@ $app_strings = array ( 'LBL_CPY_MAILING_ADDRESS' => 'Copy Mailing Address', 'LBL_CPY_OTHER_ADDRESS' => 'Copy Other Address', 'LBL_PERMISSION' => 'You are not permitted to execute this Operation', -'VTIGER' => 'vtiger', 'LBL_DIRECT_AMOUNT_DISCOUNT' => 'Direct Amount Discount', 'LBL_NO_DISCOUNT_FOR_THIS_PRODUCT' => 'No Discount for this Product', 'LBL_NO_DISCOUNT_FOR_THIS_LINE_ITEM'=> 'No Discount for this line item', @@ -821,7 +822,7 @@ $app_strings = array ( 'MSG_THANK_YOU'=>'Thank You', 'MSG_HAS_BEEN_CREATED_FOR'=>'has been created for', 'MSG_THANKS'=>'Thanks,', -'MSG_VTIGERTEAM'=>' vTiger Team', +'MSG_VTIGERTEAM'=>' coreBOS Team', 'MSG_IS_NOT_UPLOADED'=>'is not uploaded. Allowed file types - jpeg, png, jpg, pjpeg, x-png or gif', 'MSG_IMAGE_ERROR'=>'Image not found', diff --git a/include/pclzip.lib.php b/include/pclzip.lib.php new file mode 100644 index 0000000..5b84607 --- /dev/null +++ b/include/pclzip.lib.php @@ -0,0 +1,5872 @@ +zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 1); + return; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function create($p_filelist) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::create', "filelist='$p_filelist', ..."); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options detected"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Invalid number / type of arguments"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Ignore an empty filename"); + } + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_result_list); + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function add($p_filelist) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::add', "filelist='$p_filelist', ..."); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options detected"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_result_list); + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exists and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + function listContent() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::listContent', ""); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) + { + unset($p_list); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function extract() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::extract", ""); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "path='$v_path', remove_path='$v_remove_path', remove_all_path='".($v_remove_path?'true':'false')."'"); + + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, + $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + function extractByIndex($p_index) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::extractByIndex", "index='$p_index', ..."); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Option PCLZIP_OPT_EXTRACT_AS_STRING not set."); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Option PCLZIP_OPT_EXTRACT_AS_STRING set."); + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "index='$p_index', path='$v_path', remove_path='$v_remove_path', remove_all_path='".($v_remove_path?'true':'false')."'"); + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, + array (PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function delete() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::delete", ""); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Set default values + $v_options = array(); + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Call the delete fct + $v_list = array(); + if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_list); + return $v_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : deleteByIndex() + // Description : + // ***** Deprecated ***** + // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. + // -------------------------------------------------------------------------------- + function deleteByIndex($p_index) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::deleteByIndex", "index='$p_index'"); + + $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : properties() + // Description : + // This method gives the properties of the archive. + // The properties are : + // nb : Number of files in the archive + // comment : Comment associated with the archive file + // status : not_exist, ok + // Parameters : + // None + // Return Values : + // 0 on failure, + // An array with the archive properties. + // -------------------------------------------------------------------------------- + function properties() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::properties", ""); + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Default properties + $v_prop = array(); + $v_prop['comment'] = ''; + $v_prop['nb'] = 0; + $v_prop['status'] = 'not_exist'; + + // ----- Look if file exists + if (@is_file($this->zipname)) + { + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), 0); + return 0; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_prop); + return $v_prop; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : duplicate() + // Description : + // This method creates an archive by copying the content of an other one. If + // the archive already exist, it is replaced by the new one without any warning. + // Parameters : + // $p_archive : The filename of a valid archive, or + // a valid PclZip object. + // Return Values : + // 1 on success. + // 0 or a negative value on error (error code). + // -------------------------------------------------------------------------------- + function duplicate($p_archive) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::duplicate", ""); + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the $p_archive is a PclZip object + if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The parameter is valid PclZip object '".$p_archive->zipname."'"); + + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); + } + + // ----- Look if the $p_archive is a string (so a filename) + else if (is_string($p_archive)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The parameter is a filename '$p_archive'"); + + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } + else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : merge() + // Description : + // This method merge the $p_archive_to_add archive at the end of the current + // one ($this). + // If the archive ($this) does not exist, the merge becomes a duplicate. + // If the $p_archive_to_add archive does not exist, the merge is a success. + // Parameters : + // $p_archive_to_add : It can be directly the filename of a valid zip archive, + // or a PclZip object archive. + // Return Values : + // 1 on success, + // 0 or negative values on error (see below). + // -------------------------------------------------------------------------------- + function merge($p_archive_to_add) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::merge", ""); + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Look if the $p_archive_to_add is a PclZip object + if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The parameter is valid PclZip object"); + + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); + } + + // ----- Look if the $p_archive_to_add is a string (so a filename) + else if (is_string($p_archive_to_add)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The parameter is a filename"); + + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : errorCode() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorCode() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); + } + else { + return($this->error_code); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorName() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorName($p_with_code=false) + { + $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' + ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' + ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ); + + if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; + } + else { + $v_value = 'NoName'; + } + + if ($p_with_code) { + return($v_value.' ('.$this->error_code.')'); + } + else { + return($v_value); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorInfo() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorInfo($p_full=false) + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorString()); + } + else { + if ($p_full) { + return($this->errorName(true)." : ".$this->error_string); + } + else { + return($this->error_string." [code ".$this->error_code."]"); + } + } + } + // -------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------- +// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** +// ***** ***** +// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** +// -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : privCheckFormat() + // Description : + // This method check that the archive exists and is a valid zip archive. + // Several level of check exists. (futur) + // Parameters : + // $p_level : Level of check. Default 0. + // 0 : Check the first bytes (magic codes) (default value)) + // 1 : 0 + Check the central directory (futur) + // 2 : 1 + Check each file header (futur) + // Return Values : + // true on success, + // false on error, the error code is set. + // -------------------------------------------------------------------------------- + function privCheckFormat($p_level=0) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFormat", ""); + $v_result = true; + + // ----- Reset the file system cache + clearstatcache(); + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the file exits + if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo()); + return(false); + } + + // ----- Check that the file is readeable + if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo()); + return(false); + } + + // ----- Check the magic code + // TBC + + // ----- Check the central header + // TBC + + // ----- Check each file header + // TBC + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privParseOptions() + // Description : + // This internal methods reads the variable list of arguments ($p_options_list, + // $p_size) and generate an array with the options and values ($v_result_list). + // $v_requested_options contains the options that can be present and those that + // must be present. + // $v_requested_options is an array, with the option value as key, and 'optional', + // or 'mandatory' as value. + // Parameters : + // See above. + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privParseOptions", ""); + $v_result=1; + + // ----- Read the options + $i=0; + while ($i<$p_size) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Looking for table index $i, option = '".PclZipUtilOptionText($p_options_list[$i])."(".$p_options_list[$i].")'"); + + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH : + case PCLZIP_OPT_REMOVE_PATH : + case PCLZIP_OPT_ADD_PATH : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if ( is_string($p_options_list[$i+1]) + && ($p_options_list[$i+1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." set with an empty value is ignored."); + } + break; + + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that request an EREG or PREG expression + case PCLZIP_OPT_BY_EREG : + case PCLZIP_OPT_BY_PREG : + //case PCLZIP_OPT_CRYPT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT : + case PCLZIP_OPT_ADD_COMMENT : + case PCLZIP_OPT_PREPEND_COMMENT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, + "Missing parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, + "Wrong parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i+1])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is a string '".$p_options_list[$i+1]."'"); + + // ----- Remove spaces + $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i+1]); + } + else if (is_integer($p_options_list[$i+1])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an integer '".$p_options_list[$i+1]."'"); + $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an array"); + $v_work_list = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag=false; + $v_sort_value=0; + for ($j=0; $j= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT : + case PCLZIP_CB_POST_EXTRACT : + case PCLZIP_CB_PRE_ADD : + case PCLZIP_CB_POST_ADD : + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i+1]; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "call-back ".PclZipUtilOptionText($p_options_list[$i])." = '".$v_function_name."'"); + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Set the attribute + $v_result_list[$p_options_list[$i]] = $v_function_name; + $i++; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '" + .$p_options_list[$i]."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Next options + $i++; + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Detect a mandatory option : ".PclZipUtilOptionText($key)."(".$key.")"); + // ----- Look if present + if (!isset($v_result_list[$key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrParseAtt() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privFileDescrParseAtt", ""); + $v_result=1; + + // ----- For each file in the list check the attributes + foreach ($p_file_list as $v_key => $v_value) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$v_key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for attribute + switch ($v_key) { + case PCLZIP_ATT_FILE_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + + if ($p_filedescr['filename'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + break; + + case PCLZIP_ATT_FILE_NEW_SHORT_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + + if ($p_filedescr['new_short_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + break; + + case PCLZIP_ATT_FILE_NEW_FULL_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + + if ($p_filedescr['new_full_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + break; + + // ----- Look for options that takes a string + case PCLZIP_ATT_FILE_COMMENT : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['comment'] = $v_value; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + break; + + case PCLZIP_ATT_FILE_MTIME : + if (!is_integer($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['mtime'] = $v_value; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + break; + + case PCLZIP_ATT_FILE_CONTENT : + $p_filedescr['content'] = $v_value; + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '".$v_key."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Detect a mandatory option : ".PclZipUtilOptionText($key)."(".$key.")"); + // ----- Look if present + if (!isset($p_file_list[$key])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + } + } + + // end foreach + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrExpand() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrExpand(&$p_filedescr_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privFileDescrExpand", ""); + $v_result=1; + + // ----- Create a result list + $v_result_list = array(); + + // ----- Look each entry + for ($i=0; $iprivCalculateStoredFilename($v_descr, $p_options); + + // ----- Add the descriptor in result list + $v_result_list[sizeof($v_result_list)] = $v_descr; + + // ----- Look for folder + if ($v_descr['type'] == 'folder') { + // ----- List of items in folder + $v_dirlist_descr = array(); + $v_dirlist_nb = 0; + if ($v_folder_handler = @opendir($v_descr['filename'])) { + while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Looking for '".$v_item_handler."' in the directory"); + + // ----- Skip '.' and '..' + if (($v_item_handler == '.') || ($v_item_handler == '..')) { + continue; + } + + // ----- Compose the full filename + $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; + + // ----- Look for different stored filename + // Because the name of the folder was changed, the name of the + // files/sub-folders also change + if ($v_descr['stored_filename'] != $v_descr['filename']) { + if ($v_descr['stored_filename'] != '') { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; + } + else { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; + } + } + + $v_dirlist_nb++; + } + + @closedir($v_folder_handler); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to open dir '".$v_descr['filename']."' in read mode. Skipped."); + // TBC : unable to open folder in read mode + } + + // ----- Expand each element of the list + if ($v_dirlist_nb != 0) { + // ----- Expand + if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Concat the resulting list + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Merging result list (size '".sizeof($v_result_list)."') with dirlist (size '".sizeof($v_dirlist_descr)."')"); + $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "merged result list is size '".sizeof($v_result_list)."'"); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Nothing in this folder to expand."); + } + + // ----- Free local array + unset($v_dirlist_descr); + } + } + + // ----- Get the result list + $p_filedescr_list = $v_result_list; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCreate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCreate", "list"); + $v_result=1; + $v_list_detail = array(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the file in write mode + if (($v_result = $this->privOpenFd('wb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Add the list of files + $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + + // ----- Close + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAdd() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAdd", "list"); + $v_result=1; + $v_list_detail = array(); + + // ----- Look if the archive exists or is empty + if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive does not exist, or is empty, create it."); + + // ----- Do a create + $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "New offset of central dir : $v_offset"); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = $v_central_dir['comment']; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { + $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOpenFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privOpenFd($p_mode) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privOpenFd", 'mode='.$p_mode); + $v_result=1; + + // ----- Look if already open + if ($this->zip_fd != 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Open file in '.$p_mode.' mode'); + if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCloseFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privCloseFd() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCloseFd", ""); + $v_result=1; + + if ($this->zip_fd != 0) + @fclose($this->zip_fd); + $this->zip_fd = 0; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddList() + // Description : + // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is + // different from the real path of the file. This is usefull if you want to have PclTar + // running in any directory, and memorize relative path from an other directory. + // Parameters : + // $p_list : An array containing the file or directory names to add in the tar + // $p_result_list : list of added files with their properties (specially the status field) + // $p_add_dir : Path to add in the filename path archived + // $p_remove_dir : Path to remove in the filename path archived + // Return Values : + // -------------------------------------------------------------------------------- +// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) + function privAddList($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddList", "list"); + $v_result=1; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Create the Central Dir files header + for ($i=0,$v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileList() + // Description : + // Parameters : + // $p_filedescr_list : An array containing the file description + // or directory names to add in the zip + // $p_result_list : list of added files with their properties (specially the status field) + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddFileList", "filedescr_list"); + $v_result=1; + $v_header = array(); + + // ----- Recuperate the current number of elt in list + $v_nb = sizeof($p_result_list); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Before add, list have ".$v_nb." elements"); + + // ----- Loop on the files + for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header, + $p_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the file infos + $p_result_list[$v_nb++] = $v_header; + } + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "After add, list have ".$v_nb." elements"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFile($p_filedescr, &$p_header, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddFile", "filename='".$p_filedescr['filename']."'"); + $v_result=1; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + // TBC : Already done in the fileAtt check ... ? + if ($p_filename == "") { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for a stored different filename + /* TBC : Removed + if (isset($p_filedescr['stored_filename'])) { + $v_stored_filename = $p_filedescr['stored_filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'Stored filename is NOT the same "'.$v_stored_filename.'"'); + } + else { + $v_stored_filename = $p_filedescr['stored_filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'Stored filename is the same'); + } + */ + + // ----- Set the file properties + clearstatcache(); + $p_header['version'] = 20; + $p_header['version_extracted'] = 10; + $p_header['flag'] = 0; + $p_header['compression'] = 0; + $p_header['crc'] = 0; + $p_header['compressed_size'] = 0; + $p_header['filename_len'] = strlen($p_filename); + $p_header['extra_len'] = 0; + $p_header['disk'] = 0; + $p_header['internal'] = 0; + $p_header['offset'] = 0; + $p_header['filename'] = $p_filename; +// TBC : Removed $p_header['stored_filename'] = $v_stored_filename; + $p_header['stored_filename'] = $p_filedescr['stored_filename']; + $p_header['extra'] = ''; + $p_header['status'] = 'ok'; + $p_header['index'] = -1; + + // ----- Look for regular file + if ($p_filedescr['type']=='file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for regular folder + else if ($p_filedescr['type']=='folder') { + $p_header['external'] = 0x00000010; + $p_header['mtime'] = filemtime($p_filename); + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for virtual file + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = strlen($p_filedescr['content']); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header external extension '".sprintf("0x%X",$p_header['external'])."'"); + + // ----- Look for filetime + if (isset($p_filedescr['mtime'])) { + $p_header['mtime'] = $p_filedescr['mtime']; + } + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['mtime'] = mktime(); + } + else { + $p_header['mtime'] = filemtime($p_filename); + } + + // ------ Look for file comment + if (isset($p_filedescr['comment'])) { + $p_header['comment_len'] = strlen($p_filedescr['comment']); + $p_header['comment'] = $p_filedescr['comment']; + } + else { + $p_header['comment_len'] = 0; + $p_header['comment'] = ''; + } + + // ----- Look for pre-add callback + if (isset($p_options[PCLZIP_CB_PRE_ADD])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_ADD]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); + if ($v_result == 0) { + // ----- Change the file status + $p_header['status'] = "skipped"; + $v_result = 1; + } + + // ----- Update the informations + // Only some fields can be modified + if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { + $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New stored filename is '".$p_header['stored_filename']."'"); + } + } + + // ----- Look for empty stored filename + if ($p_header['stored_filename'] == "") { + $p_header['status'] = "filtered"; + } + + // ----- Check the path length + if (strlen($p_header['stored_filename']) > 0xFF) { + $p_header['status'] = 'filename_too_long'; + } + + // ----- Look if no error, or file not skipped + if ($p_header['status'] == 'ok') { + + // ----- Look for a file +// if (is_file($p_filename)) + if ( ($p_filedescr['type'] == 'file') + || ($p_filedescr['type'] == 'virtual_file')) { + + // ----- Get content from real file + if ($p_filedescr['type'] == 'file') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "'".$p_filename."' is a file"); + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the file content + $v_content = @fread($v_file, $p_header['size']); + + // ----- Close the file + @fclose($v_file); + } + else if ($p_filedescr['type'] == 'virtual_file') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Add by string"); + $v_content = $p_filedescr['content']; + } + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be compressed"); + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will be compressed"); + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Look for encryption + /* + if ((isset($p_options[PCLZIP_OPT_CRYPT])) + && ($p_options[PCLZIP_OPT_CRYPT] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File need to be crypted ...."); + + // Should be a random header + $v_header = 'xxxxxxxxxxxx'; + $v_content_compressed = PclZipUtilZipEncrypt($v_content_compressed, + $p_header['compressed_size'], + $v_header, + $p_header['crc'], + "test"); + + $p_header['compressed_size'] += 12; + $p_header['flag'] = 1; + + // ----- Add the header to the data + $v_content_compressed = $v_header.$v_content_compressed; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Size after header : ".strlen($v_content_compressed).""); + } + */ + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + } + + // ----- Look for a directory + else if ($p_filedescr['type'] == 'folder') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "'".$p_filename."' is a folder"); + // ----- Look for directory last '/' + if (@substr($p_header['stored_filename'], -1) != '/') { + $p_header['stored_filename'] .= '/'; + } + + // ----- Set the file properties + $p_header['size'] = 0; + //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked + $p_header['external'] = 0x00000010; // Value for a folder : to be checked + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) + { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + } + } + + // ----- Look for post-add callback + if (isset($p_options[PCLZIP_CB_POST_ADD])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_ADD]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); + if ($v_result == 0) { + // ----- Ignored + $v_result = 1; + } + + // ----- Update the informations + // Nothing can be modified + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCalculateStoredFilename() + // Description : + // Based on file descriptor properties and global options, this method + // calculate the filename that will be stored in the archive. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCalculateStoredFilename(&$p_filedescr, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCalculateStoredFilename", "filename='".$p_filedescr['filename']."'"); + $v_result=1; + + // ----- Working variables + $p_filename = $p_filedescr['filename']; + if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; + } + else { + $p_add_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; + } + else { + $p_remove_dir = ''; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Remove path ='".$p_remove_dir."'"); + if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + else { + $p_remove_all_dir = 0; + } + + // ----- Look for full name change + if (isset($p_filedescr['new_full_name'])) { + $v_stored_filename = $p_filedescr['new_full_name']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Changing full name of '".$p_filename."' for '".$v_stored_filename."'"); + } + + // ----- Look for path and/or short name change + else { + + // ----- Look for short name change + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'].'/'; + } + $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Changing short name of '".$p_filename."' for '".$v_stored_filename."'"); + } + else { + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } + + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Remove all path selected change '".$p_filename."' for '".$v_stored_filename."'"); + } + // ----- Look for partial path remove + else if ($p_remove_dir != "") { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Partial path to remove"); + if (substr($p_remove_dir, -1) != '/') + $p_remove_dir .= "/"; + + if ( (substr($p_filename, 0, 2) == "./") + || (substr($p_remove_dir, 0, 2) == "./")) { + + if ( (substr($p_filename, 0, 2) == "./") + && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./".$p_remove_dir; + } + if ( (substr($p_filename, 0, 2) != "./") + && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); + } + } + + $v_compare = PclZipUtilPathInclusion($p_remove_dir, + $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Path to remove is the current folder"); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Remove path '$p_remove_dir' in file '$v_stored_filename'"); + $v_stored_filename = substr($v_stored_filename, + strlen($p_remove_dir)); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Result is '$v_stored_filename'"); + } + } + } + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") + $v_stored_filename = $p_add_dir.$v_stored_filename; + else + $v_stored_filename = $p_add_dir."/".$v_stored_filename; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Add path '$p_add_dir' in file '$p_filename' = '$v_stored_filename'"); + } + } + + // ----- Filename (reduce the path of stored name) + $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); + $p_filedescr['stored_filename'] = $v_stored_filename; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Stored filename will be '".$p_filedescr['stored_filename']."', strlen ".strlen($p_filedescr['stored_filename'])); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteFileHeader", 'file="'.$p_header['filename'].'", stored as "'.$p_header['stored_filename'].'"'); + $v_result=1; + + // ----- Store the offset position of the file + $p_header['offset'] = ftell($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'File offset of the header :'.$p_header['offset']); + + // ----- Transform UNIX mtime to DOS format mdate/mtime + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + // ----- Packed data + $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, + $p_header['version_extracted'], $p_header['flag'], + $p_header['compression'], $v_mtime, $v_mdate, + $p_header['crc'], $p_header['compressed_size'], + $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len']); + + // ----- Write the first 148 bytes of the header in the archive + fputs($this->zip_fd, $v_binary_data, 30); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteCentralFileHeader", 'file="'.$p_header['filename'].'", stored as "'.$p_header['stored_filename'].'"'); + $v_result=1; + + // TBC + //for(reset($p_header); $key = key($p_header); next($p_header)) { + // //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "header[$key] = ".$p_header[$key]); + //} + + // ----- Transform UNIX mtime to DOS format mdate/mtime + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment size : \''.$p_header['comment_len'].'\''); + + // ----- Packed data + $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, + $p_header['version'], $p_header['version_extracted'], + $p_header['flag'], $p_header['compression'], + $v_mtime, $v_mdate, $p_header['crc'], + $p_header['compressed_size'], $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len'], $p_header['comment_len'], + $p_header['disk'], $p_header['internal'], + $p_header['external'], $p_header['offset']); + + // ----- Write the 42 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 46); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + if ($p_header['comment_len'] != 0) + { + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteCentralHeader", 'nb_entries='.$p_nb_entries.', size='.$p_size.', offset='.$p_offset.', comment="'.$p_comment.'"'); + $v_result=1; + + // ----- Packed data + $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, + $p_nb_entries, $p_size, + $p_offset, strlen($p_comment)); + + // ----- Write the 22 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 22); + + // ----- Write the variable fields + if (strlen($p_comment) != 0) + { + fputs($this->zip_fd, $p_comment, strlen($p_comment)); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privList() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privList(&$p_list) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privList", "list"); + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of Central Dir + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Offset : ".$v_central_dir['offset']."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_central_dir['offset'])) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'"); + + // ----- Read each entry + for ($i=0; $i<$v_central_dir['entries']; $i++) + { + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + $v_header['index'] = $i; + + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privConvertHeader2FileInfo() + // Description : + // This function takes the file informations from the central directory + // entries and extract the interesting parameters that will be given back. + // The resulting file infos are set in the array $p_info + // $p_info['filename'] : Filename with full path. Given by user (add), + // extracted in the filesystem (extract). + // $p_info['stored_filename'] : Stored filename in the archive. + // $p_info['size'] = Size of the file. + // $p_info['compressed_size'] = Compressed size of the file. + // $p_info['mtime'] = Last modification date of the file. + // $p_info['comment'] = Comment associated with the file. + // $p_info['folder'] = true/false : indicates if the entry is a folder or not. + // $p_info['status'] = status of the action on the file. + // $p_info['crc'] = CRC of the file content. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privConvertHeader2FileInfo($p_header, &$p_info) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privConvertHeader2FileInfo", "Filename='".$p_header['filename']."'"); + $v_result=1; + + // ----- Get the interesting attributes + $p_info['filename'] = $p_header['filename']; + $p_info['stored_filename'] = $p_header['stored_filename']; + $p_info['size'] = $p_header['size']; + $p_info['compressed_size'] = $p_header['compressed_size']; + $p_info['mtime'] = $p_header['mtime']; + $p_info['comment'] = $p_header['comment']; + $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); + $p_info['index'] = $p_header['index']; + $p_info['status'] = $p_header['status']; + $p_info['crc'] = $p_header['crc']; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractByRule() + // Description : + // Extract a file or directory depending of rules (by index, by name, ...) + // Parameters : + // $p_file_list : An array where will be placed the properties of each + // extracted file + // $p_path : Path to add while writing the extracted files + // $p_remove_path : Path to remove (from the file memorized path) while writing the + // extracted files. If the path does not match the file path, + // the file is extracted with its memorized path. + // $p_remove_path does not apply to 'list' mode. + // $p_path and $p_remove_path are commulative. + // Return Values : + // 1 on success,0 or less on error (see error code list) + // -------------------------------------------------------------------------------- + function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privExtractByRule", "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'"); + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check the path + if ( ($p_path == "") + || ( (substr($p_path, 0, 1) != "/") + && (substr($p_path, 0, 3) != "../") + && (substr($p_path,1,2)!=":/"))) + $p_path = "./".$p_path; + + // ----- Reduce the path last (and duplicated) '/' + if (($p_path != "./") && ($p_path != "/")) + { + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'"); + $p_path = substr($p_path, 0, strlen($p_path)-1); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]"); + } + } + + // ----- Look for path to remove format (should end by /) + if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) + { + $p_remove_path .= '/'; + } + $p_remove_path_size = strlen($p_remove_path); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result = $this->privOpenFd('rb')) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + + // ----- Read each entry + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Read next file header entry : '$i'"); + + // ----- Read next Central dir entry + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position before rewind : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the index + $v_header['index'] = $i; + + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); + + // ----- Look for the specific extract rules + $v_extract = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByName'"); + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The directory is in the file path"); + $v_extract = true; + } + } + // ----- Look for a filename + elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The file is the right one."); + $v_extract = true; + } + } + } + + // ----- Look for extract by ereg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract by ereg '".$p_options[PCLZIP_OPT_BY_EREG]."'"); + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_extract = true; + } + } + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByEreg'"); + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_extract = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByIndex'"); + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found as part of an index range"); + $v_extract = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Do not look this index range for next loop"); + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Index range is greater than index, stop loop"); + break; + } + } + } + + // ----- Look for no rule, which means extract all the archive + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with no rule (extract all)"); + $v_extract = true; + } + + // ----- Check compression method + if ( ($v_extract) + && ( ($v_header['compression'] != 8) + && ($v_header['compression'] != 0))) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported compression method (".$v_header['compression'].")"); + $v_header['status'] = 'unsupported_compression'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, + "Filename '".$v_header['stored_filename']."' is " + ."compressed by an unsupported compression " + ."method (".$v_header['compression'].") "); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported file encryption"); + $v_header['status'] = 'unsupported_encryption'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, + "Unsupported encryption for " + ." filename '".$v_header['stored_filename'] + ."'"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "No need for extract"); + $v_result = $this->privConvertHeader2FileInfo($v_header, + $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + $v_extract = false; + } + + // ----- Look for real extraction + if ($v_extract) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file '".$v_header['filename']."', index '$i'"); + + // ----- Go to the file position + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_header['offset'])) + { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for extraction in standard output + elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) + && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for normal extraction + else { + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, + $p_path, $p_remove_path, + $p_remove_all_path, + $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } + } + + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFile() + // Description : + // Parameters : + // Return Values : + // + // 1 : ... ? + // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback + // -------------------------------------------------------------------------------- + function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFile', "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'"); + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'"); + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for all path to remove + if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external']&0x00000010)==0x00000010) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The entry is a folder : need to be filtered"); + + $p_entry['status'] = "filtered"; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "All path is removed"); + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); + } + + // ----- Look for path to remove + else if ($p_remove_path != "") + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Look for some path to remove"); + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The folder is the same as the removed path '".$p_entry['filename']."'"); + + // ----- Change the file status + $p_entry['status'] = "filtered"; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '".$p_entry['filename']."'"); + + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Resulting file is '".$p_entry['filename']."'"); + } + } + + // ----- Add the path + if ($p_path != '') { + $p_entry['filename'] = $p_path."/".$p_entry['filename']; + } + + // ----- Check a base_dir_restriction + if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Check the extract directory restriction"); + $v_inclusion + = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], + $p_entry['filename']); + if ($v_inclusion == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_EXTRACT_DIR_RESTRICTION is selected, file is outside restriction"); + + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, + "Filename '".$p_entry['filename']."' is " + ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'"); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'"); + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Look for specific actions while the file exist + if (file_exists($p_entry['filename'])) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$p_entry['filename']."' already exists"); + + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is a directory"); + + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, + "Filename '".$p_entry['filename']."' is " + ."already used by an existing directory"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + // ----- Look if file is write protected + else if (!is_writeable($p_entry['filename'])) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is write protected"); + + // ----- Change the file status + $p_entry['status'] = "write_protected"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Filename '".$p_entry['filename']."' exists " + ."and is write protected"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Look if the extracted file is older + else if (filemtime($p_entry['filename']) > $p_entry['mtime']) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is newer (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")"); + // ----- Change the file status + if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) + && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_REPLACE_NEWER is selected, file will be replaced"); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be replaced"); + $p_entry['status'] = "newer_exist"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Newer version of '".$p_entry['filename']."' exists " + ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is older than the extrated one - will be replaced by the extracted one (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")"); + } + } + + // ----- Check the directory availability and create it if necessary + else { + if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) + $v_dir_to_check = $p_entry['filename']; + else if (!strstr($p_entry['filename'], "/")) + $v_dir_to_check = ""; + else + $v_dir_to_check = dirname($p_entry['filename']); + + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '".$p_entry['filename']."'"); + + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; + + // ----- Return + ////--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + //return $v_result; + $v_result = 1; + } + } + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file"); + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode"); + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read '".$p_entry['size']."' bytes"); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read $v_read_size bytes"); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Closing the destination file + fclose($v_dest_file); + + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); + + + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (Compression method ".$p_entry['compression'].")"); + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File is encrypted"); + /* + // ----- Read the encryption header + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read 12 encryption header bytes"); + $v_encryption_header = @fread($this->zip_fd, 12); + + // ----- Read the encrypted & compressed file in a buffer + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read '".($p_entry['compressed_size']-12)."' compressed & encrypted bytes"); + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']-12); + + // ----- Decrypt the buffer + $this->privDecrypt($v_encryption_header, $v_buffer, + $p_entry['compressed_size']-12, $p_entry['crc']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Buffer is '".$v_buffer."'"); + */ + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read '".$p_entry['compressed_size']."' compressed bytes"); + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + } + + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === FALSE) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to inflate compressed file"); + + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode"); + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); + + // ----- Closing the destination file + @fclose($v_dest_file); + + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "chmod option activated '".$p_options[PCLZIP_OPT_SET_CHMOD]."'"); + + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done"); + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileInOutput() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileInOutput(&$p_entry, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileInOutput', ""); + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'"); + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'"); + } + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'"); + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes"); + + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Reading '".$p_entry['size']."' bytes"); + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done"); + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileAsString() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileAsString(&$p_entry, &$p_string) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileAsString', "p_entry['filename']='".$p_entry['filename']."'"); + $v_result=1; + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'"); + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file in string (with path) '".$p_entry['filename']."', size '$v_header[size]'"); + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file +// if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes"); + + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (compression method '".$p_entry['compression']."')"); + + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === FALSE) { + // TBC + } + } + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done"); + } + else { + // TBC : error : can not extract a folder in a string + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadFileHeader", ""); + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'"); + $v_data = unpack('Vid', $v_binary_data); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'"); + + // ----- Check signature + if ($v_data['id'] != 0x04034b50) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid File header"); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 26); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 26) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Extract the values + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header : '".$v_binary_data."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header (Hex) : '".bin2hex($v_binary_data)."'"); + $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + + // ----- Get filename + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "File name length : ".$v_data['filename_len']); + $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename : \''.$p_header['filename'].'\''); + + // ----- Get extra_fields + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extra field length : ".$v_data['extra_len']); + if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); + } + else { + $p_header['extra'] = ''; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Extra field : \''.bin2hex($p_header['extra']).'\''); + + // ----- Extract properties + $p_header['version_extracted'] = $v_data['version']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : ('.$p_header['version_extracted'].') \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\''); + $p_header['compression'] = $v_data['compression']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compression method : \''.$p_header['compression'].'\''); + $p_header['size'] = $v_data['size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_header['size'].'\''); + $p_header['compressed_size'] = $v_data['compressed_size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_header['compressed_size'].'\''); + $p_header['crc'] = $v_data['crc']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\''); + $p_header['flag'] = $v_data['flag']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Flag : \''.$p_header['flag'].'\''); + $p_header['filename_len'] = $v_data['filename_len']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename_len : \''.$p_header['filename_len'].'\''); + + // ----- Recuperate date in UNIX format + $p_header['mdate'] = $v_data['mdate']; + $p_header['mtime'] = $v_data['mtime']; + if ($p_header['mdate'] && $p_header['mtime']) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + else + { + $p_header['mtime'] = time(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + + // TBC + //for(reset($v_data); $key = key($v_data); next($v_data)) { + // //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Attribut[$key] = ".$v_data[$key]); + //} + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set the status field + $p_header['status'] = "ok"; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadCentralFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadCentralFileHeader", ""); + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'"); + $v_data = unpack('Vid', $v_binary_data); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'"); + + // ----- Check signature + if ($v_data['id'] != 0x02014b50) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid Central Dir File signature"); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 42); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 42) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Extract the values + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header : '".$v_binary_data."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header (Hex) : '".bin2hex($v_binary_data)."'"); + $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); + + // ----- Get filename + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File name length : ".$p_header['filename_len']); + if ($p_header['filename_len'] != 0) + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); + else + $p_header['filename'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Filename : \''.$p_header['filename'].'\''); + + // ----- Get extra + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Extra length : ".$p_header['extra_len']); + if ($p_header['extra_len'] != 0) + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); + else + $p_header['extra'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Extra : \''.$p_header['extra'].'\''); + + // ----- Get comment + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Comment length : ".$p_header['comment_len']); + if ($p_header['comment_len'] != 0) + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); + else + $p_header['comment'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Comment : \''.$p_header['comment'].'\''); + + // ----- Extract properties + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version : \''.($p_header['version']/10).'.'.($p_header['version']%10).'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Size : \''.$p_header['size'].'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Compressed Size : \''.$p_header['compressed_size'].'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Flag : \''.$p_header['flag'].'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Offset : \''.$p_header['offset'].'\''); + + // ----- Recuperate date in UNIX format + //if ($p_header['mdate'] && $p_header['mtime']) + // TBC : bug : this was ignoring time with 0/0/0 + if (1) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + else + { + $p_header['mtime'] = time(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set default status to ok + $p_header['status'] = 'ok'; + + // ----- Look if it is a directory + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Internal (Hex) : '".sprintf("Ox%04X", $p_header['internal'])."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "External (Hex) : '".sprintf("Ox%04X", $p_header['external'])."' (".(($p_header['external']&0x00000010)==0x00000010?'is a folder':'is a file').')'); + if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Force folder external : \''.sprintf("Ox%04X", $p_header['external']).'\''); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Header of filename : \''.$p_header['filename'].'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFileHeaders() + // Description : + // Parameters : + // Return Values : + // 1 on success, + // 0 on error; + // -------------------------------------------------------------------------------- + function privCheckFileHeaders(&$p_local_header, &$p_central_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFileHeaders", ""); + $v_result=1; + + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename" : TBC To Be Completed'); + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "version_extracted" : TBC To Be Completed'); + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "flag" : TBC To Be Completed'); + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "compression" : TBC To Be Completed'); + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "mtime" : TBC To Be Completed'); + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename_len" : TBC To Be Completed'); + } + + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Purpose bit flag bit 3 set !'); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'File size, compression size and crc found in central header'); + $p_local_header['size'] = $p_central_header['size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_local_header['size'].'\''); + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_local_header['compressed_size'].'\''); + $p_local_header['crc'] = $p_central_header['crc']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_local_header['crc']).'\''); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadEndCentralDir() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadEndCentralDir(&$p_central_dir) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadEndCentralDir", ""); + $v_result=1; + + // ----- Go to the end of the zip file + $v_size = filesize($this->zipname); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Size of the file :$v_size"); + @fseek($this->zip_fd, $v_size); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position at end of zip file : \''.ftell($this->zip_fd).'\''); + if (@ftell($this->zip_fd) != $v_size) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- First try : look if this is an archive with no commentaries (most of the time) + // in this case the end of central dir is at 22 bytes of the file end + $v_found = 0; + if ($v_size > 26) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Look for central dir with no comment'); + @fseek($this->zip_fd, $v_size-22); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after min central position : \''.ftell($this->zip_fd).'\''); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Binary data is : '".sprintf("%08x", $v_binary_data)."'"); + $v_data = @unpack('Vid', $v_binary_data); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'"); + + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found central dir at the default position."); + $v_found = 1; + } + + $v_pos = ftell($this->zip_fd); + } + + // ----- Go back to the maximum possible size of the Central Dir End Record + if (!$v_found) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Start extended search of end central dir'); + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) + $v_maximum_size = $v_size; + @fseek($this->zip_fd, $v_size-$v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after max central position : \''.ftell($this->zip_fd).'\''); + + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) + { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + $v_bytes = ($v_bytes << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Found End Central Dir signature at position : \''.ftell($this->zip_fd).'\''); + $v_pos++; + break; + } + + $v_pos++; + } + + // ----- Look if not found end of central dir + if ($v_pos == $v_size) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to find End of Central Dir Record signature"); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Read the first 18 bytes of the header + $v_binary_data = fread($this->zip_fd, 18); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 18) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Extract the values + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record : '".$v_binary_data."'"); + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record (Hex) : '".bin2hex($v_binary_data)."'"); + $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + + // ----- Check the global size + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Comment length : ".$v_data['comment_size']); + if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The central dir is not at the end of the archive. Some trailing bytes exists after the archive."); + + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, + 'The central dir is not at the end of the archive.' + .' Some trailing bytes exists after the archive.'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Get comment + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment size : \''.$v_data['comment_size'].'\''); + if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); + } + else + $p_central_dir['comment'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment : \''.$p_central_dir['comment'].'\''); + + $p_central_dir['entries'] = $v_data['entries']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries : \''.$p_central_dir['entries'].'\''); + $p_central_dir['disk_entries'] = $v_data['disk_entries']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries for this disk : \''.$p_central_dir['disk_entries'].'\''); + $p_central_dir['offset'] = $v_data['offset']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Offset of Central Dir : \''.$p_central_dir['offset'].'\''); + $p_central_dir['size'] = $v_data['size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size of Central Dir : \''.$p_central_dir['size'].'\''); + $p_central_dir['disk'] = $v_data['disk']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Disk number : \''.$p_central_dir['disk'].'\''); + $p_central_dir['disk_start'] = $v_data['disk_start']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Start disk number : \''.$p_central_dir['disk_start'].'\''); + + // TBC + //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { + // //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "central_dir[$key] = ".$p_central_dir[$key]); + //} + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDeleteByRule() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDeleteByRule(&$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDeleteByRule", ""); + $v_result=1; + $v_list_detail = array(); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + + // ----- Scan all the files + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Read each entry + $v_header_list = array(); + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Read next file header entry (index '$i')"); + + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename (index '$i') : '".$v_header_list[$v_nb_extracted]['stored_filename']."'"); + + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; + + // ----- Look for the specific extract rules + $v_found = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByName'"); + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The directory is in the file path"); + $v_found = true; + } + elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ + && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The entry is the searched directory"); + $v_found = true; + } + } + // ----- Look for a filename + elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The file is the right one."); + $v_found = true; + } + } + } + + // ----- Look for extract by ereg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract by ereg '".$p_options[PCLZIP_OPT_BY_EREG]."'"); + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_found = true; + } + } + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByEreg'"); + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_found = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByIndex'"); + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found as part of an index range"); + $v_found = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Do not look this index range for next loop"); + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Index range is greater than index, stop loop"); + break; + } + } + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "No argument mean remove all file"); + $v_found = true; + } + + // ----- Look for deletion + if ($v_found) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$v_header_list[$v_nb_extracted]['stored_filename']."', index '$i' need to be deleted"); + unset($v_header_list[$v_nb_extracted]); + } + else + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$v_header_list[$v_nb_extracted]['stored_filename']."', index '$i' will not be deleted"); + $v_nb_extracted++; + } + } + + // ----- Look if something need to be deleted + if ($v_nb_extracted > 0) { + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); + + // ----- Open the temporary zip file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary write mode"); + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + $this->privCloseFd(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look which file need to be kept + for ($i=0; $izip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, + $v_header_list[$i]) != 1) { + // TBC + } + unset($v_local_header); + + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Offset for this file is '".$v_header_list[$i]['offset']."'"); + + // ----- Read/write the data block + if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "New offset of central dir : $v_offset"); + + // ----- Re-Create the Central Dir files header + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Creates the new central directory"); + for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Creates the central directory footer"); + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Close + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Destroy the temporary archive + unset($v_temp_zip); + } + + // ----- Remove every files : reset the file + else if ($v_central_dir['entries'] != 0) { + $this->privCloseFd(); + + if (($v_result = $this->privOpenFd('wb')) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + $this->privCloseFd(); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDirCheck() + // Description : + // Check if a directory exists, if not it creates it and all the parents directory + // which may be useful. + // Parameters : + // $p_dir : Directory path to check. + // Return Values : + // 1 : OK + // -1 : Unable to create directory + // -------------------------------------------------------------------------------- + function privDirCheck($p_dir, $p_is_dir=false) + { + $v_result = 1; + + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDirCheck", "entry='$p_dir', is_dir='".($p_is_dir?"true":"false")."'"); + + // ----- Remove the final '/' + if (($p_is_dir) && (substr($p_dir, -1)=='/')) + { + $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Looking for entry '$p_dir'"); + + // ----- Check the directory availability + if ((is_dir($p_dir)) || ($p_dir == "")) + { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, "'$p_dir' is a directory"); + return 1; + } + + // ----- Extract parent directory + $p_parent_dir = dirname($p_dir); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Parent directory is '$p_parent_dir'"); + + // ----- Just a check + if ($p_parent_dir != $p_dir) + { + // ----- Look for parent directory + if ($p_parent_dir != "") + { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) + { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + } + } + + // ----- Create the directory + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Create directory '$p_dir'"); + if (!@mkdir($p_dir, 0777)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result, "Directory '$p_dir' created"); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privMerge() + // Description : + // If $p_archive_to_add does not exist, the function exit with a success result. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privMerge(&$p_archive_to_add) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privMerge", "archive='".$p_archive_to_add->zipname."'"); + $v_result=1; + + // ----- Look if the archive_to_add exists + if (!is_file($p_archive_to_add->zipname)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive to add does not exist. End of merge."); + + // ----- Nothing to merge, so merge is a success + $v_result = 1; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look if the archive exists + if (!is_file($this->zipname)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive does not exist, duplicate the archive_to_add."); + + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in zip : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in zip : ".ftell($this->zip_fd)."'"); + + // ----- Open the archive_to_add file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open archive_to_add in binary read mode"); + if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) + { + $this->privCloseFd(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir_to_add = array(); + if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in archive_to_add : ".ftell($p_archive_to_add->zip_fd)."'"); + @rewind($p_archive_to_add->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in archive_to_add : ".ftell($p_archive_to_add->zip_fd)."'"); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the files from the archive_to_add into the temporary file + $v_size = $v_central_dir_to_add['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_zip_temp_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "New offset of central dir : $v_offset"); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the block of file headers from the archive_to_add + $v_size = $v_central_dir_to_add['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Merge the file comments + $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + + // ----- Calculate the size of the (new) central header + $v_size = @ftell($v_zip_temp_fd)-$v_offset; + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive fd + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; + + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDuplicate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDuplicate($p_archive_filename) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDuplicate", "archive_filename='$p_archive_filename'"); + $v_result=1; + + // ----- Look if the $p_archive_filename exists + if (!is_file($p_archive_filename)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive to duplicate does not exist. End of duplicate."); + + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('wb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Open the temporary file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) + { + $this->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = filesize($p_archive_filename); + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read $v_read_size bytes"); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorLog() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorLog($p_error_code=0, $p_error_string='') + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); + } + else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorReset() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorReset() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); + } + else { + $this->error_code = 0; + $this->error_string = ''; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDecrypt() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDecrypt($p_encryption_header, &$p_buffer, $p_size, $p_crc) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privDecrypt', "size=".$p_size.""); + $v_result=1; + + // ----- To Be Modified ;-) + $v_pwd = "test"; + + $p_buffer = PclZipUtilZipDecrypt($p_buffer, $p_size, $p_encryption_header, + $p_crc, $v_pwd); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDisableMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDisableMagicQuotes() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privDisableMagicQuotes', ""); + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look if already done + if ($this->magic_quotes_status != -1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote already disabled"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Get and memorize the magic_quote value + $this->magic_quotes_status = @get_magic_quotes_runtime(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Current magic_quotes_runtime status is '".($this->magic_quotes_status==0?'disable':'enable')."'"); + + // ----- Disable magic_quotes + if ($this->magic_quotes_status == 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Disable magic_quotes"); + @set_magic_quotes_runtime(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privSwapBackMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privSwapBackMagicQuotes() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privSwapBackMagicQuotes', ""); + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look if something to do + if ($this->magic_quotes_status != -1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote not modified"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Swap back magic_quotes + if ($this->magic_quotes_status == 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Enable back magic_quotes"); + @set_magic_quotes_runtime($this->magic_quotes_status); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + } + // End of class + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathReduction() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilPathReduction($p_dir) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilPathReduction", "dir='$p_dir'"); + $v_result = ""; + + // ----- Look for not empty path + if ($p_dir != "") { + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i=sizeof($v_list)-1; $i>=0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } + else if ($v_list[$i] == "..") { + $v_skip++; + } + else if ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/".$v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid path is unchanged"); + $v_skip = 0; + } + } + // ----- Last '/' i.e. indicates a directory + else if ($i == (sizeof($v_list)-1)) { + $v_result = $v_list[$i]; + } + // ----- Double '/' inside the path + else { + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } + else { + // ----- Look for item to skip + if ($v_skip > 0) { + $v_skip--; + } + else { + $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + } + } + } + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../'.$v_result; + $v_skip--; + } + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathInclusion() + // Description : + // This function indicates if the path $p_path is under the $p_dir tree. Or, + // said in an other way, if the file or sub-dir $p_path is inside the dir + // $p_dir. + // The function indicates also if the path is exactly the same as the dir. + // This function supports path with duplicated '/' like '//', but does not + // support '.' or '..' statements. + // Parameters : + // Return Values : + // 0 if $p_path is not inside directory $p_dir + // 1 if $p_path is inside directory $p_dir + // 2 if $p_path is exactly the same as $p_dir + // -------------------------------------------------------------------------------- + function PclZipUtilPathInclusion($p_dir, $p_path) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilPathInclusion", "dir='$p_dir', path='$p_path'"); + $v_result = 1; + + // ----- Look for path beginning by ./ + if ( ($p_dir == '.') + || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_dir '".$p_dir."'"); + } + if ( ($p_path == '.') + || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_path '".$p_path."'"); + } + + // ----- Explode dir and path by directory separator + $v_list_dir = explode("/", $p_dir); + $v_list_dir_size = sizeof($v_list_dir); + $v_list_path = explode("/", $p_path); + $v_list_path_size = sizeof($v_list_path); + + // ----- Study directories paths + $i = 0; + $j = 0; + while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Working on dir($i)='".$v_list_dir[$i]."' and path($j)='".$v_list_path[$j]."'"); + + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } + + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Items ($i,$j) are different"); + $v_result = 0; + } + + // ----- Next items + $i++; + $j++; + } + + // ----- Look if everything seems to be the same + if ($v_result) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Look for tie break"); + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Looking on dir($i)='".($i < $v_list_dir_size?$v_list_dir[$i]:'')."' and path($j)='".($j < $v_list_path_size?$v_list_path[$j]:'')."'"); + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } + else if ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilCopyBlock() + // Description : + // Parameters : + // $p_mode : read/write compression mode + // 0 : src & dest normal + // 1 : src gzip, dest normal + // 2 : src normal, dest gzip + // 3 : src & dest gzip + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilCopyBlock", "size=$p_size, mode=$p_mode"); + $v_result = 1; + + if ($p_mode==0) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Src offset before read :".(@ftell($p_src))); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Dest offset before write :".(@ftell($p_dest))); + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Src offset after read :".(@ftell($p_src))); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Dest offset after write :".(@ftell($p_dest))); + } + else if ($p_mode==1) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==2) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==3) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilRename() + // Description : + // This function tries to do a simple rename() function. If it fails, it + // tries to copy the $p_src file in a new $p_dest file and then unlink the + // first one. + // Parameters : + // $p_src : Old filename + // $p_dest : New filename + // Return Values : + // 1 on success, 0 on failure. + // -------------------------------------------------------------------------------- + function PclZipUtilRename($p_src, $p_dest) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilRename", "source=$p_src, destination=$p_dest"); + $v_result = 1; + + // ----- Try to rename the files + if (!@rename($p_src, $p_dest)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to rename file, try copy+unlink"); + + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to copy file"); + $v_result = 0; + } + else if (!@unlink($p_src)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to unlink old filename"); + $v_result = 0; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilOptionText() + // Description : + // Translate option value in text. Mainly for debug purpose. + // Parameters : + // $p_option : the option value. + // Return Values : + // The option text value. + // -------------------------------------------------------------------------------- + function PclZipUtilOptionText($p_option) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilOptionText", "option='".$p_option."'"); + + $v_list = get_defined_constants(); + for (reset($v_list); $v_key = key($v_list); next($v_list)) { + $v_prefix = substr($v_key, 0, 10); + if (( ($v_prefix == 'PCLZIP_OPT') + || ($v_prefix == 'PCLZIP_CB_') + || ($v_prefix == 'PCLZIP_ATT')) + && ($v_list[$v_key] == $p_option)) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_key); + return $v_key; + } + } + + $v_result = 'Unknown'; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilTranslateWinPath() + // Description : + // Translate windows path by replacing '\' by '/' and optionally removing + // drive letter. + // Parameters : + // $p_path : path to translate. + // $p_remove_disk_letter : true | false + // Return Values : + // The path translated. + // -------------------------------------------------------------------------------- + function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) + { + if (stristr(php_uname(), 'windows')) { + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position+1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } + } + return $p_path; + } + // -------------------------------------------------------------------------------- + + +?> diff --git a/include/utils/CommonUtils.php b/include/utils/CommonUtils.php old mode 100644 new mode 100755 index 2e0fed3..d8bcce5 --- a/include/utils/CommonUtils.php +++ b/include/utils/CommonUtils.php @@ -3278,12 +3278,39 @@ function getMenuStructure($selectModule = '') { return $resultant_array; } - -function getReturnPath($host){ - $arr=explode('.',$host); - unset($arr[0]); - $domain=implode('.',$arr); - $Return_Path='noreply@'.$domain; - return $Return_Path; +function getReturnPath($host, $from_email) { + $returnname = 'info'; + $returnpath = $from_email; + // Remove the trailing protocol information + if (preg_match("/[^:]+:\/\/(.*)/", $host, $m)) { + $host = $m[1]; + } + // Remove the port address if any + if (preg_match("/([^:]+):.*/", $host, $m)) { + $host = $m[1]; + } + // Remove any extra-spaces + $host = trim($host); + + // Review if the host is not local + if (!in_array(strtolower($host), array('localhost'))) { + list($from_name, $from_domain) = explode('@', $from_email); + + //strip [,] from domain name in case ip address is used as domain: xyz@[192.45.32.67] + preg_replace("/[\[\]]/",$from_domain,$from_domain); + + // If from-email domain is not matching (or sub-domain) of host + // reset the return-path + if (strpos($host, $from_domain)== false) { + $from_domain = trim($from_domain); + + if(preg_match( '/^((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))$/', $host)){ + $returnpath = $returnname . '@[' . $host.']'; + }else{ + $returnpath = $returnname . '@' . $host; + } + } + } + return $returnpath; } ?> \ No newline at end of file diff --git a/include/utils/DetailViewUtils.php b/include/utils/DetailViewUtils.php index 5151d58..b03a14b 100755 --- a/include/utils/DetailViewUtils.php +++ b/include/utils/DetailViewUtils.php @@ -61,9 +61,7 @@ function getDetailViewOutputHtml($uitype, $fieldname, $fieldlabel, $col_fields, $parent_id = $col_fields[$fieldname]; if (!empty($parent_id)) { $parent_module = getSalesEntityType($parent_id); - $valueTitle = $parent_module; - if ($app_strings[$valueTitle]) - $valueTitle = $app_strings[$valueTitle]; + $valueTitle = getTranslatedString($parent_module,$parent_module); $displayValueArray = getEntityName($parent_module, $parent_id); if (!empty($displayValueArray)) { @@ -71,8 +69,14 @@ function getDetailViewOutputHtml($uitype, $fieldname, $fieldlabel, $col_fields, $displayValue = $value; } } + // vtlib customization: For listview javascript triggers + $modMetaInfo=getEntityFieldNames($parent_module); + $modEName=(is_array($modMetaInfo['fieldname']) ? $modMetaInfo['fieldname'][0] : $modMetaInfo['fieldname']); + $vtlib_metainfo = ""; + // END $label_fld = array($fieldlabel, - "$displayValue"); + "$displayValue$vtlib_metainfo"); } else { $moduleSpecificMessage = 'MODULE_NOT_SELECTED'; if ($mod_strings[$moduleSpecificMessage] != "") { diff --git a/include/utils/InventoryUtils.php b/include/utils/InventoryUtils.php index e7da975..91ece5c 100644 --- a/include/utils/InventoryUtils.php +++ b/include/utils/InventoryUtils.php @@ -107,7 +107,7 @@ function sendPrdStckMail($product_id,$upd_qty,$prod_name,$qtyinstk,$qty,$module) { //send mail to the handler $handler = getRecordOwnerId($product_id); - $handler_name = getOwnerName($handler); + $handler_name = getOwnerName(array_shift(array_values($handler))); if(vtws_isRecordOwnerUser($handler)) { $to_address = getUserEmail($handler); } else { diff --git a/include/utils/ListViewUtils.php b/include/utils/ListViewUtils.php old mode 100644 new mode 100755 index 9f50c28..aa79ddc --- a/include/utils/ListViewUtils.php +++ b/include/utils/ListViewUtils.php @@ -3785,7 +3785,6 @@ function getListViewDeleteLink($module, $entity_id, $relatedlist, $returnset) { $del_link .= "&parenttab=" . $tabname . "&return_viewname=" . $viewname . $url; // vtlib customization: override default delete link for custom modules - $requestModule = $current_module; $requestAction = vtlib_purify($_REQUEST['action']); $isCustomModule = vtlib_isCustomModule($requestModule); @@ -3816,9 +3815,10 @@ function getEntityId($module, $entityName) { $entityidfield = $adb->query_result($result, 0, 'entityidfield'); if (!(strpos($fieldsname, ',') === false)) { $fieldlists = explode(',', $fieldsname); - $fieldsname = "concat("; + $fieldsname = "trim(concat("; // Add trim function to weed-out extra character values $fieldsname = $fieldsname . implode(",' ',", $fieldlists); - $fieldsname = $fieldsname . ")"; + $fieldsname = $fieldsname . "))"; + $entityName = trim($entityName); // Trim the input to be consistent in comparison } if ($entityName != '') { diff --git a/include/utils/MergeUtils.php b/include/utils/MergeUtils.php new file mode 100644 index 0000000..6a36d90 --- /dev/null +++ b/include/utils/MergeUtils.php @@ -0,0 +1,166 @@ +extract(PCLZIP_OPT_PATH,$wordtemplatedownloadpath.'/'.$temp_dir) == 0) + { + die("Error s: ".$archive->errorInfo(true)); + } + //delete the template + //unlink($wordtemplatedownloadpath.'/'.$filename); + return $temp_dir; +} + +function packen($filename,$wordtemplatedownloadpath,$temp_dir, $concontent,$stylecontent) +{ + //global $filename, $wordtemplatedownloadpath; + //write a new content.xml + $handle=fopen($wordtemplatedownloadpath.'/'.$temp_dir.'/content.xml',"w"); + fwrite($handle,$concontent); + fclose($handle); + + //write a new styles.xml + $handle2=fopen($wordtemplatedownloadpath.'/'.$temp_dir.'/styles.xml',"w"); + fwrite($handle2,$stylecontent); + fclose($handle2); + + $archive = new PclZip($wordtemplatedownloadpath.'/'.$filename); + //make a new archive (or .odt file) + $v_list = $archive->add($wordtemplatedownloadpath.'/'.$temp_dir,PCLZIP_OPT_REMOVE_PATH, $wordtemplatedownloadpath.'/'.$temp_dir); + if ($v_list == 0) + { + die("Error : ".$archive->errorInfo(true)); + } +} + +function remove_dir($dir) +{ + $handle = opendir($dir); + while (false!==($item = readdir($handle))) + { + if($item != '.' && $item != '..') + { + if(is_dir($dir.'/'.$item)) + { + remove_dir($dir.'/'.$item); + } + else + { + unlink($dir.'/'.$item); + } + } + } + closedir($handle); + if(rmdir($dir)) + { + $success = true; + } + return $success; +} + + +/** +* @see http://sourceforge.net/projects/phprtf +*/ +function utf8Unicode($str) { + return unicodeToEntitiesPreservingAscii(utf8ToUnicode($str)); +} + + +/** +* @see http://sourceforge.net/projects/phprtf +*/ +function unicodeToEntitiesPreservingAscii($unicode) { + $entities = ''; + foreach( $unicode as $value ) { + if ($value != 65279) { + $entities .= ( $value > 127 ) ? '\uc0\u' . $value . ' ' : chr( $value ); + } + } + return $entities; +} +/** +* @see http://sourceforge.net/projects/phprtf +* @see http://www.randomchaos.com/documents/?source=php_and_unicode +*/ +function utf8ToUnicode($str) { + $unicode = array(); + $values = array(); + $lookingFor = 1; + + for ($i = 0; $i < strlen($str); $i++ ) { + $thisValue = ord($str[$i]); + + if ($thisValue < 128) { + $unicode[] = $thisValue; + } else { + if ( count( $values ) == 0 ) { + $lookingFor = ( $thisValue < 224 ) ? 2 : 3; + } + + $values[] = $thisValue; + + if ( count( $values ) == $lookingFor ) { + $number = ( $lookingFor == 3 ) ? + ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ): + ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 ); + $unicode[] = $number; + $values = array(); + $lookingFor = 1; + } + } + } + return $unicode; +} + + +?> diff --git a/include/utils/SearchUtils.php b/include/utils/SearchUtils.php old mode 100644 new mode 100755 index 942d75d..d8c991e --- a/include/utils/SearchUtils.php +++ b/include/utils/SearchUtils.php @@ -872,7 +872,7 @@ function getSearchURL($input) { if(empty($advft_criteria)) return $urlString; $advft_criteria_groups = vtlib_purify($input['advft_criteria_groups']); - $urlString .= '&advft_criteria='.$advft_criteria.'&advft_criteria_groups='.$advft_criteria_groups.'&searchtype=advance'; + $urlString .= '&advft_criteria='.urlencode($advft_criteria).'&advft_criteria_groups='.urlencode($advft_criteria_groups).'&searchtype=advance'; } elseif($input['type']=='dbrd'){ if(isset($input['leadsource'])) { @@ -933,7 +933,7 @@ function getSearchURL($input) { $urlString .= "&operator=".vtlib_purify($input['operator']); } } - return to_html($urlString); + return $urlString; } /**This function is returns the where conditions for dashboard and shows the records when clicked on dashboard graph @@ -1081,6 +1081,18 @@ function getUnifiedWhere($listquery,$module,$search_val){ $columnname = "accountname"; $tablename = "vtiger_account"; } + if($module == 'HelpDesk' && $columnname == 'parent_id') { + $columnname = "accountname"; + $tablename = "vtiger_account"; + if(strstr($listquery,$tablename)){ + if($where != ''){ + $where .= " OR "; + } + $where .= $tablename.".".$columnname." LIKE '". formatForSqlLike($search_val) ."'"; + } + $columnname = "firstname"; + $tablename = "vtiger_contactdetails"; + } // END //Before form the where condition, check whether the table for the field has been added in the listview query diff --git a/include/utils/UserInfoUtil.php b/include/utils/UserInfoUtil.php index d9148b9..a2bfb29 100755 --- a/include/utils/UserInfoUtil.php +++ b/include/utils/UserInfoUtil.php @@ -1472,7 +1472,7 @@ $log->debug("Entering getProfileTabsPermission(".$profileid.") method ..."); // Once that is done, Webmails need to be removed permanently. $emailsTabId = getTabid('Emails'); $webmailsTabid = getTabid('Webmails'); - if(array_key_exists($emailsTabId, $copy)) { + if(array_key_exists($emailsTabId, $copy) and !empty($webmailsTabid)) { $copy[$webmailsTabid] = $copy[$emailsTabId]; } diff --git a/include/utils/VTCacheUtils.php b/include/utils/VTCacheUtils.php index 2226a1e..78af886 100644 --- a/include/utils/VTCacheUtils.php +++ b/include/utils/VTCacheUtils.php @@ -46,18 +46,6 @@ class VTCacheUtils { self::$_alltabrows_cache = $tabrows; } - /** Block information caching */ - static $_blocklabel_cache = array(); - static function updateBlockLabelWithId($label, $id) { - self::$_blocklabel_cache[$id] = $label; - } - static function lookupBlockLabelWithId($id) { - if (isset(self::$_blocklabel_cache[$id])) { - return self::$_blocklabel_cache[$id]; - } - return false; - } - /** Field information caching */ static $_fieldinfo_cache = array(); static function updateFieldInfo($tabid, $fieldname, $fieldid, $fieldlabel, @@ -109,18 +97,6 @@ class VTCacheUtils { return false; } - /** Entityname information */ - static $_module_entityname_cache = array(); - static function updateEntityNameInfo($module, $data) { - self::$_module_entityname_cache[$module] = $data; - } - static function lookupEntityNameInfo($module) { - if (isset(self::$_module_entityname_cache[$module])) { - return self::$_module_entityname_cache[$module]; - } - return false; - } - /** Module active column fields caching */ static $_module_columnfields_cache = array(); static function updateModuleColumnFields($module, $column_fields) { diff --git a/include/utils/VtlibUtils.php b/include/utils/VtlibUtils.php index fdec4e4..c079140 100644 --- a/include/utils/VtlibUtils.php +++ b/include/utils/VtlibUtils.php @@ -540,12 +540,14 @@ function vtlib_purify($input, $ignore=false) { global $__htmlpurifier_instance, $root_directory, $default_charset; static $purified_cache = array(); - if(!is_array($input)) { + + if (!is_array($input)) { // thank you Boris and Adam (from developers list) $md5OfInput = md5($input); if (array_key_exists($md5OfInput, $purified_cache)) { return $purified_cache[$md5OfInput]; } } + $use_charset = $default_charset; $use_root_directory = $root_directory; @@ -573,9 +575,9 @@ function vtlib_purify($input, $ignore=false) { } } else { // Simple type $value = $__htmlpurifier_instance->purify($input); - $purified_cache[$md5OfInput] = $value; } } + $purified_cache[$md5OfInput] = $value; } $value = str_replace('&','&',$value); return $value; @@ -622,11 +624,11 @@ function vtlib_module_icon($modulename){ * @return $string/false */ function vtlib_purifyForSql($string, $skipEmpty=true) { - $pattern = "/^[_a-zA-Z0-9.]+$/"; - if ((empty($string) && $skipEmpty) || preg_match($pattern, $string)) { - return $string; - } - return false; + $pattern = "/^[_a-zA-Z0-9.]+$/"; + if ((empty($string) && $skipEmpty) || preg_match($pattern, $string)) { + return $string; + } + return false; } ?> diff --git a/include/utils/utils.php b/include/utils/utils.php old mode 100644 new mode 100755 index d99e155..594276a --- a/include/utils/utils.php +++ b/include/utils/utils.php @@ -1,5141 +1,5134 @@ -debug("Entering return_name(".$row.",".$first_column.",".$last_column.") method ..."); - $first_name = ""; - $last_name = ""; - $full_name = ""; - - if(isset($row[$first_column])) - { - $first_name = stripslashes($row[$first_column]); - } - - if(isset($row[$last_column])) - { - $last_name = stripslashes($row[$last_column]); - } - - $full_name = $first_name; - - // If we have a first name and we have a last name - if($full_name != "" && $last_name != "") - { - // append a space, then the last name - $full_name .= " ".$last_name; - } - // If we have no first name, but we have a last name - else if($last_name != "") - { - // append the last name without the space. - $full_name .= $last_name; - } - - $log->debug("Exiting return_name method ..."); - return $full_name; -} - -/** Function to return language - * @returns $languages -- languages:: Type string - * -*/ - -function get_languages() -{ - global $log; - $log->debug("Entering get_languages() method ..."); - global $languages; - $log->debug("Exiting get_languages method ..."); - return $languages; -} - -/** Function to return language - * @param $key -- key:: Type string - * @returns $languages -- languages:: Type string - * -*/ - -//seems not used -function get_language_display($key) -{ - global $log; - $log->debug("Entering get_language_display(".$key.") method ..."); - global $languages; - $log->debug("Exiting get_language_display method ..."); - return $languages[$key]; -} - -/** Function returns the user array - * @param $assigned_user_id -- assigned_user_id:: Type string - * @returns $user_list -- user list:: Type array - * -*/ - -function get_assigned_user_name(&$assigned_user_id) -{ - global $log; - $log->debug("Entering get_assigned_user_name(".$assigned_user_id.") method ..."); - $user_list = &get_user_array(false,""); - if(isset($user_list[$assigned_user_id])) - { - $log->debug("Exiting get_assigned_user_name method ..."); - return $user_list[$assigned_user_id]; - } - - $log->debug("Exiting get_assigned_user_name method ..."); - return ""; -} - -/** Function returns the user key in user array - * @param $add_blank -- boolean:: Type boolean - * @param $status -- user status:: Type string - * @param $assigned_user -- user id:: Type string - * @param $private -- sharing type:: Type string - * @returns $user_array -- user array:: Type array - * -*/ - -//used in module file -function get_user_array($add_blank=true, $status="Active", $assigned_user="",$private="") -{ - global $log; - $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); - global $current_user; - if(isset($current_user) && $current_user->id != '') - { - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - } - static $user_array = null; - $module=$_REQUEST['module']; - - if($user_array == null) - { - require_once('include/database/PearDatabase.php'); - $db = PearDatabase::getInstance(); - $temp_result = Array(); - // Including deleted vtiger_users for now. - if (empty($status)) { - $query = "SELECT id, user_name from vtiger_users"; - $params = array(); - } - else { - if($private == 'private') - { - $log->debug("Sharing is Private. Only the current user should be listed"); - $query = "select id as id,user_name as user_name,first_name,last_name from vtiger_users where id=? and status='Active' union select vtiger_user2role.userid as id,vtiger_users.user_name as user_name , - vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name - from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ? and status='Active' union - select shareduserid as id,vtiger_users.user_name as user_name , - vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name from vtiger_tmp_write_user_sharing_per inner join vtiger_users on vtiger_users.id=vtiger_tmp_write_user_sharing_per.shareduserid where status='Active' and vtiger_tmp_write_user_sharing_per.userid=? and vtiger_tmp_write_user_sharing_per.tabid=?"; - $params = array($current_user->id, $current_user_parent_role_seq."::%", $current_user->id, getTabid($module)); - } - else - { - $log->debug("Sharing is Public. All vtiger_users should be listed"); - $query = "SELECT id, user_name,first_name,last_name from vtiger_users WHERE status=?"; - $params = array($status); - } - } - if (!empty($assigned_user)) { - $query .= " OR id=?"; - array_push($params, $assigned_user); - } - - $query .= " order by user_name ASC"; - - $result = $db->pquery($query, $params, true, "Error filling in user array: "); - - if ($add_blank==true){ - // Add in a blank row - $temp_result[''] = ''; - } - - // Get the id and the name. - while($row = $db->fetchByAssoc($result)) - { - $temp_result[$row['id']] = getFullNameFromArray('Users', $row); - } - - $user_array = &$temp_result; - } - - $log->debug("Exiting get_user_array method ..."); - - return $user_array; -} - -function get_group_array($add_blank=true, $status="Active", $assigned_user="",$private="") -{ - global $log; - $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); - global $current_user; - if(isset($current_user) && $current_user->id != '') - { - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - } - static $group_array = null; - $module=$_REQUEST['module']; - - if($group_array == null) - { - require_once('include/database/PearDatabase.php'); - $db = PearDatabase::getInstance(); - $temp_result = Array(); - // Including deleted vtiger_users for now. - $log->debug("Sharing is Public. All vtiger_users should be listed"); - $query = "SELECT groupid, groupname from vtiger_groups"; - $params = array(); - - if($private == 'private'){ - - $query .= " WHERE groupid=?"; - $params = array( $current_user->id); - - if(count($current_user_groups) != 0) { - $query .= " OR vtiger_groups.groupid in (".generateQuestionMarks($current_user_groups).")"; - array_push($params, $current_user_groups); - } - $log->debug("Sharing is Private. Only the current user should be listed"); - $query .= " union select vtiger_group2role.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_group2role inner join vtiger_groups on vtiger_groups.groupid=vtiger_group2role.groupid inner join vtiger_role on vtiger_role.roleid=vtiger_group2role.roleid where vtiger_role.parentrole like ?"; - array_push($params, $current_user_parent_role_seq."::%"); - - if(count($current_user_groups) != 0) { - $query .= " union select vtiger_groups.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_groups inner join vtiger_group2rs on vtiger_groups.groupid=vtiger_group2rs.groupid where vtiger_group2rs.roleandsubid in (".generateQuestionMarks($parent_roles).")"; - array_push($params, $parent_roles); - } - - $query .= " union select sharedgroupid as groupid,vtiger_groups.groupname as groupname from vtiger_tmp_write_group_sharing_per inner join vtiger_groups on vtiger_groups.groupid=vtiger_tmp_write_group_sharing_per.sharedgroupid where vtiger_tmp_write_group_sharing_per.userid=?"; - array_push($params, $current_user->id); - - $query .= " and vtiger_tmp_write_group_sharing_per.tabid=?"; - array_push($params, getTabid($module)); - } - $query .= " order by groupname ASC"; - - $result = $db->pquery($query, $params, true, "Error filling in user array: "); - - if ($add_blank==true){ - // Add in a blank row - $temp_result[''] = ''; - } - - // Get the id and the name. - while($row = $db->fetchByAssoc($result)) - { - $temp_result[$row['groupid']] = $row['groupname']; - } - - $group_array = &$temp_result; - } - - $log->debug("Exiting get_user_array method ..."); - return $group_array; -} -/** Function skips executing arbitary commands given in a string - * @param $string -- string:: Type string - * @param $maxlength -- maximun length:: Type integer - * @returns $string -- escaped string:: Type string - * -*/ - -function clean($string, $maxLength) -{ - global $log; - $log->debug("Entering clean(".$string.",". $maxLength.") method ..."); - $string = substr($string, 0, $maxLength); - $log->debug("Exiting clean method ..."); - return escapeshellcmd($string); -} - -/** - * Copy the specified request variable to the member variable of the specified object. - * Do no copy if the member variable is already set. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function safe_map($request_var, & $focus, $always_copy = false) -{ - global $log; - $log->debug("Entering safe_map(".$request_var.",".get_class($focus).",".$always_copy.") method ..."); - safe_map_named($request_var, $focus, $request_var, $always_copy); - $log->debug("Exiting safe_map method ..."); -} - -/** - * Copy the specified request variable to the member variable of the specified object. - * Do no copy if the member variable is already set. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function safe_map_named($request_var, & $focus, $member_var, $always_copy) -{ - global $log; - $log->debug("Entering safe_map_named(".$request_var.",".get_class($focus).",".$member_var.",".$always_copy.") method ..."); - if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) { - $log->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var"); - $focus->$member_var = $_REQUEST[$request_var]; - } - $log->debug("Exiting safe_map_named method ..."); -} - -/** This function retrieves an application language file and returns the array of strings included in the $app_list_strings var. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are using the current language, do not call this function unless you are loading it for the first time */ - -function return_app_list_strings_language($language) -{ - global $log; - $log->debug("Entering return_app_list_strings_language(".$language.") method ..."); - global $app_list_strings, $default_language, $log, $translation_string_prefix; - $temp_app_list_strings = $app_list_strings; - $language_used = $language; - - @include("include/language/$language.lang.php"); - if(!isset($app_list_strings)) - { - $log->warn("Unable to find the application language file for language: ".$language); - require("include/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($app_list_strings)) - { - $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_app_list_strings_language method ..."); - return null; - } - - - $return_value = $app_list_strings; - $app_list_strings = $temp_app_list_strings; - - $log->debug("Exiting return_app_list_strings_language method ..."); - return $return_value; -} - -/** - * Retrieve the app_currency_strings for the required language. - */ -function return_app_currency_strings_language($language) { - global $log; - $log->debug("Entering return_app_currency_strings_language(".$language.") method ..."); - global $app_currency_strings, $default_language, $log, $translation_string_prefix; - // Backup the value first - $temp_app_currency_strings = $app_currency_strings; - @include("include/language/$language.lang.php"); - if(!isset($app_currency_strings)) - { - $log->warn("Unable to find the application language file for language: ".$language); - require("include/language/$default_language.lang.php"); - $language_used = $default_language; - } - if(!isset($app_currency_strings)) - { - $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_app_currency_strings_language method ..."); - return null; - } - $return_value = $app_currency_strings; - - // Restore the value back - $app_currency_strings = $temp_app_currency_strings; - - $log->debug("Exiting return_app_currency_strings_language method ..."); - return $return_value; -} - -/** This function retrieves an application language file and returns the array of strings included. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are using the current language, do not call this function unless you are loading it for the first time */ -function return_application_language($language) -{ - global $log; - $log->debug("Entering return_application_language(".$language.") method ..."); - global $app_strings, $default_language, $log, $translation_string_prefix; - $temp_app_strings = $app_strings; - $language_used = $language; - - checkFileAccessForInclusion("include/language/$language.lang.php"); - @include("include/language/$language.lang.php"); - if(!isset($app_strings)) - { - $log->warn("Unable to find the application language file for language: ".$language); - require("include/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($app_strings)) - { - $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_application_language method ..."); - return null; - } - - // If we are in debug mode for translating, turn on the prefix now! - if($translation_string_prefix) - { - foreach($app_strings as $entry_key=>$entry_value) - { - $app_strings[$entry_key] = $language_used.' '.$entry_value; - } - } - - $return_value = $app_strings; - $app_strings = $temp_app_strings; - - $log->debug("Exiting return_application_language method ..."); - return $return_value; -} - -/** This function retrieves a module's language file and returns the array of strings included. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are in the current module, do not call this function unless you are loading it for the first time */ -function return_module_language($language, $module) -{ - global $log; - $log->debug("Entering return_module_language(".$language.",". $module.") method ..."); - global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; - static $cachedModuleStrings = array(); - - if(!empty($cachedModuleStrings[$module])) { - $log->debug("Exiting return_module_language method ..."); - return $cachedModuleStrings[$module]; - } - - $temp_mod_strings = $mod_strings; - $language_used = $language; - - @include("modules/$module/language/$language.lang.php"); - if(!isset($mod_strings)) - { - $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); - if($default_language == 'en_us') { - checkFileAccessForInclusion("modules/$module/language/$default_language.lang.php"); - require("modules/$module/language/$default_language.lang.php"); - $language_used = $default_language; - } else { - @include("modules/$module/language/$default_language.lang.php"); - if(!isset($mod_strings)) { - checkFileAccessForInclusion("modules/$module/language/en_us.lang.php"); - require("modules/$module/language/en_us.lang.php"); - $language_used = 'en_us'; - } else { - $language_used = $default_language; - } - } - } - - if(!isset($mod_strings)) - { - $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_module_language method ..."); - return null; - } - - // If we are in debug mode for translating, turn on the prefix now! - if($translation_string_prefix) - { - foreach($mod_strings as $entry_key=>$entry_value) - { - $mod_strings[$entry_key] = $language_used.' '.$entry_value; - } - } - - $return_value = $mod_strings; - $mod_strings = $temp_mod_strings; - - $log->debug("Exiting return_module_language method ..."); - $cachedModuleStrings[$module] = $return_value; - return $return_value; -} - -/*This function returns the mod_strings for the current language and the specified module -*/ - -function return_specified_module_language($language, $module) -{ - global $log; - global $default_language, $translation_string_prefix; - - @include("modules/$module/language/$language.lang.php"); - if(!isset($mod_strings)) - { - $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); - require("modules/$module/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($mod_strings)) - { - $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_module_language method ..."); - return null; - } - - $return_value = $mod_strings; - - $log->debug("Exiting return_module_language method ..."); - return $return_value; -} - -/** This function retrieves an application language file and returns the array of strings included in the $mod_list_strings var. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - * If you are using the current language, do not call this function unless you are loading it for the first time */ -function return_mod_list_strings_language($language,$module) -{ - global $log; - $log->debug("Entering return_mod_list_strings_language(".$language.",".$module.") method ..."); - global $mod_list_strings, $default_language, $log, $currentModule,$translation_string_prefix; - - $language_used = $language; - $temp_mod_list_strings = $mod_list_strings; - - if($currentModule == $module && isset($mod_list_strings) && $mod_list_strings != null) - { - $log->debug("Exiting return_mod_list_strings_language method ..."); - return $mod_list_strings; - } - - @include("modules/$module/language/$language.lang.php"); - - if(!isset($mod_list_strings)) - { - $log->fatal("Unable to load the application list language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_mod_list_strings_language method ..."); - return null; - } - - $return_value = $mod_list_strings; - $mod_list_strings = $temp_mod_list_strings; - - $log->debug("Exiting return_mod_list_strings_language method ..."); - return $return_value; -} - -/** This function retrieves a theme's language file and returns the array of strings included. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function return_theme_language($language, $theme) -{ - global $log; - $log->debug("Entering return_theme_language(".$language.",". $theme.") method ..."); - global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; - - $language_used = $language; - - @include("themes/$theme/language/$current_language.lang.php"); - if(!isset($theme_strings)) - { - $log->warn("Unable to find the theme file for language: ".$language." and theme: ".$theme); - require("themes/$theme/language/$default_language.lang.php"); - $language_used = $default_language; - } - - if(!isset($theme_strings)) - { - $log->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)"); - $log->debug("Exiting return_theme_language method ..."); - return null; - } - - // If we are in debug mode for translating, turn on the prefix now! - if($translation_string_prefix) - { - foreach($theme_strings as $entry_key=>$entry_value) - { - $theme_strings[$entry_key] = $language_used.' '.$entry_value; - } - } - - $log->debug("Exiting return_theme_language method ..."); - return $theme_strings; -} - - - -/** If the session variable is defined and is not equal to "" then return it. Otherwise, return the default value. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. -*/ -function return_session_value_or_default($varname, $default) -{ - global $log; - $log->debug("Entering return_session_value_or_default(".$varname.",". $default.") method ..."); - if(isset($_SESSION[$varname]) && $_SESSION[$varname] != "") - { - $log->debug("Exiting return_session_value_or_default method ..."); - return $_SESSION[$varname]; - } - - $log->debug("Exiting return_session_value_or_default method ..."); - return $default; -} - -/** - * Creates an array of where restrictions. These are used to construct a where SQL statement on the query - * It looks for the variable in the $_REQUEST array. If it is set and is not "" it will create a where clause out of it. - * @param &$where_clauses - The array to append the clause to - * @param $variable_name - The name of the variable to look for an add to the where clause if found - * @param $SQL_name - [Optional] If specified, this is the SQL column name that is used. If not specified, the $variable_name is used as the SQL_name. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function append_where_clause(&$where_clauses, $variable_name, $SQL_name = null) -{ - global $log; - $log->debug("Entering append_where_clause(".$where_clauses.",".$variable_name.",".$SQL_name.") method ..."); - if($SQL_name == null) - { - $SQL_name = $variable_name; - } - - if(isset($_REQUEST[$variable_name]) && $_REQUEST[$variable_name] != "") - { - array_push($where_clauses, "$SQL_name like '$_REQUEST[$variable_name]%'"); - } - $log->debug("Exiting append_where_clause method ..."); -} - -/** - * Generate the appropriate SQL based on the where clauses. - * @param $where_clauses - An Array of individual where clauses stored as strings - * @returns string where_clause - The final SQL where clause to be executed. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function generate_where_statement($where_clauses) -{ - global $log; - $log->debug("Entering generate_where_statement(".$where_clauses.") method ..."); - $where = ""; - foreach($where_clauses as $clause) - { - if($where != "") - $where .= " and "; - $where .= $clause; - } - - $log->info("Here is the where clause for the list view: $where"); - $log->debug("Exiting generate_where_statement method ..."); - return $where; -} - -/** - * A temporary method of generating GUIDs of the correct format for our DB. - * @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee - * - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. -*/ -function create_guid() -{ - global $log; - $log->debug("Entering create_guid() method ..."); - $microTime = microtime(); - list($a_dec, $a_sec) = explode(" ", $microTime); - - $dec_hex = sprintf("%x", $a_dec* 1000000); - $sec_hex = sprintf("%x", $a_sec); - - ensure_length($dec_hex, 5); - ensure_length($sec_hex, 6); - - $guid = ""; - $guid .= $dec_hex; - $guid .= create_guid_section(3); - $guid .= '-'; - $guid .= create_guid_section(4); - $guid .= '-'; - $guid .= create_guid_section(4); - $guid .= '-'; - $guid .= create_guid_section(4); - $guid .= '-'; - $guid .= $sec_hex; - $guid .= create_guid_section(6); - - $log->debug("Exiting create_guid method ..."); - return $guid; - -} - -/** Function to create guid section for a given character - * @param $characters -- characters:: Type string - * @returns $return -- integer:: Type integer`` - */ -function create_guid_section($characters) -{ - global $log; - $log->debug("Entering create_guid_section(".$characters.") method ..."); - $return = ""; - for($i=0; $i<$characters; $i++) - { - $return .= sprintf("%x", rand(0,15)); - } - $log->debug("Exiting create_guid_section method ..."); - return $return; -} - -/** Function to ensure length - * @param $string -- string:: Type string - * @param $length -- length:: Type string - */ - -function ensure_length(&$string, $length) -{ - global $log; - $log->debug("Entering ensure_length(".$string.",". $length.") method ..."); - $strlen = strlen($string); - if($strlen < $length) - { - $string = str_pad($string,$length,"0"); - } - else if($strlen > $length) - { - $string = substr($string, 0, $length); - } - $log->debug("Exiting ensure_length method ..."); -} -/* -function microtime_diff($a, $b) { - global $log; - $log->debug("Entering microtime_diff(".$a.",". $b.") method ..."); - list($a_dec, $a_sec) = explode(" ", $a); - list($b_dec, $b_sec) = explode(" ", $b); - $log->debug("Exiting microtime_diff method ..."); - return $b_sec - $a_sec + $b_dec - $a_dec; -} - */ - -/** - * Return the display name for a theme if it exists. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_theme_display($theme) { - global $log; - $log->debug("Entering get_theme_display(".$theme.") method ..."); - global $theme_name, $theme_description; - $temp_theme_name = $theme_name; - $temp_theme_description = $theme_description; - - if (is_file("./themes/$theme/config.php")) { - @include("./themes/$theme/config.php"); - $return_theme_value = $theme_name; - } - else { - $return_theme_value = $theme; - } - $theme_name = $temp_theme_name; - $theme_description = $temp_theme_description; - - $log->debug("Exiting get_theme_display method ..."); - return $return_theme_value; -} - -/** - * Return an array of directory names. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_themes() { - global $log; - $log->debug("Entering get_themes() method ..."); - if ($dir = @opendir("./themes")) { - while (($file = readdir($dir)) !== false) { - if ($file != ".." && $file != "." && $file != "CVS" && $file != "Attic" && $file != "akodarkgem" && $file != "bushtree" && $file != "coolblue" && $file != "Amazon" && $file != "busthree" && $file != "Aqua" && $file != "nature" && $file != "orange" && $file != "blue") { - if(is_dir("./themes/".$file)) { - if(!($file[0] == '.')) { - // set the initial theme name to the filename - $name = $file; - - // if there is a configuration class, load that. - if(is_file("./themes/$file/config.php")) - { - require_once("./themes/$file/config.php"); - } - - if(is_file("./themes/$file/style.css")) - { - $filelist[$file] = $name; - } - } - } - } - } - closedir($dir); - } - - ksort($filelist); - $log->debug("Exiting get_themes method ..."); - return $filelist; -} - - - -/** - * Create javascript to clear values of all elements in a form. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_clear_form_js () { -global $log; -$log->debug("Entering get_clear_form_js () method ..."); -$the_script = << - - -EOQ; - -$log->debug("Exiting get_clear_form_js method ..."); -return $the_script; -} - -/** - * Create javascript to set the cursor focus to specific vtiger_field in a form - * when the screen is rendered. The vtiger_field name is currently hardcoded into the - * the function. - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_set_focus_js () { -global $log; -$log->debug("Entering set_focus() method ..."); -//TODO Clint 5/20 - Make this function more generic so that it can take in the target form and vtiger_field names as variables -$the_script = << - - -EOQ; - -$log->debug("Exiting get_set_focus_js method ..."); -return $the_script; -} - -/** - * Very cool algorithm for sorting multi-dimensional arrays. Found at http://us2.php.net/manual/en/function.array-multisort.php - * Syntax: $new_array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...); - * Explanation: $array is the array you want to sort, 'col1' is the name of the column - * you want to sort, SORT_FLAGS are : SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING - * you can repeat the 'col',FLAG,FLAG, as often you want, the highest prioritiy is given to - * the first - so the array is sorted by the last given column first, then the one before ... - * Example: $array = array_csort($array,'town','age',SORT_DESC,'name'); - * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function array_csort() { - global $log; - $log->debug("Entering array_csort() method ..."); - $args = func_get_args(); - $marray = array_shift($args); - $i = 0; - - $msortline = "return(array_multisort("; - foreach ($args as $arg) { - $i++; - if (is_string($arg)) { - foreach ($marray as $row) { - $sortarr[$i][] = $row[$arg]; - } - } else { - $sortarr[$i] = $arg; - } - $msortline .= "\$sortarr[".$i."],"; - } - $msortline .= "\$marray));"; - - eval($msortline); - $log->debug("Exiting array_csort method ..."); - return $marray; -} - -/** Function to set default varibles on to the global variable - * @param $defaults -- default values:: Type array - */ -function set_default_config(&$defaults) -{ - global $log; - $log->debug("Entering set_default_config(".$defaults.") method ..."); - - foreach ($defaults as $name=>$value) - { - if ( ! isset($GLOBALS[$name]) ) - { - $GLOBALS[$name] = $value; - } - } - $log->debug("Exiting set_default_config method ..."); -} - -$toHtml = array( - '"' => '"', - '<' => '<', - '>' => '>', - '& ' => '& ', - "'" => ''', - '' => '\r', - '\r\n'=>'\n', - -); - -/** Function to convert the given string to html - * @param $string -- string:: Type string - * @param $ecnode -- boolean:: Type boolean - * @returns $string -- string:: Type string - * - */ -function to_html($string, $encode=true) -{ - global $log,$default_charset; - //$log->debug("Entering to_html(".$string.",".$encode.") method ..."); - global $toHtml; - $action = vtlib_purify($_REQUEST['action']); - $search = vtlib_purify($_REQUEST['search']); - - $doconvert = false; - - if($_REQUEST['module'] != 'Settings' && $_REQUEST['file'] != 'ListView' && $_REQUEST['module'] != 'Portal' && $_REQUEST['module'] != "Reports")// && $_REQUEST['module'] != 'Emails') - $ajax_action = $_REQUEST['module'].'Ajax'; - - if(is_string($string)) - { - if($action != 'CustomView' && $action != 'Export' && $action != $ajax_action && $action != 'LeadConvertToEntities' && $action != 'CreatePDF' && $action != 'ConvertAsFAQ' && $_REQUEST['module'] != 'Dashboard' && $action != 'CreateSOPDF' && $action != 'SendPDFMail' && (!isset($_REQUEST['submode'])) ) - { - $doconvert = true; - } - else if($search == true) - { - // Fix for tickets #4647, #4648. Conversion required in case of search results also. - $doconvert = true; - } - if ($doconvert == true) - { - if(strtolower($default_charset) == 'utf-8') - $string = htmlentities($string, ENT_QUOTES, $default_charset); - else - $string = preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); - } - } - - //$log->debug("Exiting to_html method ..."); - return $string; -} - -/** Function to get the tablabel for a given id - * @param $tabid -- tab id:: Type integer - * @returns $string -- string:: Type string -*/ - -function getTabname($tabid) -{ - global $log; - $log->debug("Entering getTabname(".$tabid.") method ..."); - $log->info("tab id is ".$tabid); - global $adb; - $sql = "select tablabel from vtiger_tab where tabid=?"; - $result = $adb->pquery($sql, array($tabid)); - $tabname= $adb->query_result($result,0,"tablabel"); - $log->debug("Exiting getTabname method ..."); - return $tabname; - -} - -/** Function to get the tab module name for a given id - * @param $tabid -- tab id:: Type integer - * @returns $string -- string:: Type string - * - */ - -function getTabModuleName($tabid) -{ - global $log; - $log->debug("Entering getTabModuleName(".$tabid.") method ..."); - - // Lookup information in cache first - $tabname = VTCacheUtils::lookupModulename($tabid); - if($tabname === false) { - if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) { - include('tabdata.php'); - $tabname = array_search($tabid,$tab_info_array); - - if($tabname == false) { - global $adb; - $sql = "select name from vtiger_tab where tabid=?"; - $result = $adb->pquery($sql, array($tabid)); - $tabname= $adb->query_result($result,0,"name"); - } - - // Update information to cache for re-use - VTCacheUtils::updateTabidInfo($tabid, $tabname); - - } else { - $log->info("tab id is ".$tabid); - global $adb; - $sql = "select name from vtiger_tab where tabid=?"; - $result = $adb->pquery($sql, array($tabid)); - $tabname= $adb->query_result($result,0,"name"); - - // Update information to cache for re-use - VTCacheUtils::updateTabidInfo($tabid, $tabname); - } - } - $log->debug("Exiting getTabModuleName method ..."); - return $tabname; -} - -/** Function to get column fields for a given module - * @param $module -- module:: Type string - * @returns $column_fld -- column field :: Type array - * - */ - -function getColumnFields($module) -{ - global $log; - $log->debug("Entering getColumnFields(".$module.") method ..."); - $log->debug("in getColumnFields ".$module); - - // Lookup in cache for information - $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); - - if($cachedModuleFields === false) { - global $adb; - $tabid = getTabid($module); - if ($module == 'Calendar') { - $tabid = array('9','16'); - } - - // Let us pick up all the fields first so that we can cache information - $sql = "SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence - FROM vtiger_field WHERE tabid in (" . generateQuestionMarks($tabid) . ")"; - - $result = $adb->pquery($sql, array($tabid)); - $noofrows = $adb->num_rows($result); - - if($noofrows) { - while($resultrow = $adb->fetch_array($result)) { - // Update information to cache for re-use - VTCacheUtils::updateFieldInfo( - $resultrow['tabid'], $resultrow['fieldname'], $resultrow['fieldid'], - $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], - $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence'] - ); - } - } - - // For consistency get information from cache - $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); - } - - if($module == 'Calendar') { - $cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events'); - if($cachedModuleFields == false) $cachedModuleFields = $cachedEventsFields; - else $cachedModuleFields = array_merge($cachedModuleFields, $cachedEventsFields); - } - - $column_fld = array(); - if($cachedModuleFields) { - foreach($cachedModuleFields as $fieldinfo) { - $column_fld[$fieldinfo['fieldname']] = ''; - } - } - - $log->debug("Exiting getColumnFields method ..."); - return $column_fld; -} - -/** Function to get a users's mail id - * @param $userid -- userid :: Type integer - * @returns $email -- email :: Type string - * - */ - -function getUserEmail($userid) -{ - global $log; - $log->debug("Entering getUserEmail(".$userid.") method ..."); - $log->info("in getUserEmail ".$userid); - - global $adb; - if($userid != '') - { - $sql = "select email1 from vtiger_users where id=?"; - $result = $adb->pquery($sql, array($userid)); - $email = $adb->query_result($result,0,"email1"); - } - $log->debug("Exiting getUserEmail method ..."); - return $email; -} - -/** Function to get a userid for outlook - * @param $username -- username :: Type string - * @returns $user_id -- user id :: Type integer - */ - -//outlook security -function getUserId_Ol($username) -{ - global $log; - $log->debug("Entering getUserId_Ol(".$username.") method ..."); - $log->info("in getUserId_Ol ".$username); - - global $adb; - $sql = "select id from vtiger_users where user_name=?"; - $result = $adb->pquery($sql, array($username)); - $num_rows = $adb->num_rows($result); - if($num_rows > 0) - { - $user_id = $adb->query_result($result,0,"id"); - } - else - { - $user_id = 0; - } - $log->debug("Exiting getUserId_Ol method ..."); - return $user_id; -} - - -/** Function to get a action id for a given action name - * @param $action -- action name :: Type string - * @returns $actionid -- action id :: Type integer - */ - -//outlook security - -function getActionid($action) -{ - global $log; - $log->debug("Entering getActionid(".$action.") method ..."); - global $adb; - $log->info("get Actionid ".$action); - $actionid = ''; - if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) - { - include('tabdata.php'); - $actionid= $action_id_array[$action]; - } - else - { - $query="select * from vtiger_actionmapping where actionname=?"; - $result =$adb->pquery($query, array($action)); - $actionid=$adb->query_result($result,0,'actionid'); - - } - $log->info("action id selected is ".$actionid ); - $log->debug("Exiting getActionid method ..."); - return $actionid; -} - -/** Function to get a action for a given action id - * @param $action id -- action id :: Type integer - * @returns $actionname-- action name :: Type string - */ - - -function getActionname($actionid) -{ - global $log; - $log->debug("Entering getActionname(".$actionid.") method ..."); - global $adb; - - $actionname=''; - - if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) - { - include('tabdata.php'); - $actionname= $action_name_array[$actionid]; - } - else - { - - $query="select * from vtiger_actionmapping where actionid=? and securitycheck=0"; - $result =$adb->pquery($query, array($actionid)); - $actionname=$adb->query_result($result,0,"actionname"); - } - $log->debug("Exiting getActionname method ..."); - return $actionname; -} - -/** Function to get a assigned user id for a given entity - * @param $record -- entity id :: Type integer - * @returns $user_id -- user id :: Type integer - */ - -function getUserId($record) -{ - global $log; - $log->debug("Entering getUserId(".$record.") method ..."); - $log->info("in getUserId ".$record); - - global $adb; - $user_id=$adb->query_result($adb->pquery("select * from vtiger_crmentity where crmid = ?", array($record)),0,'smownerid'); - $log->debug("Exiting getUserId method ..."); - return $user_id; -} - -/** Function to get a user id or group id for a given entity - * @param $record -- entity id :: Type integer - * @returns $ownerArr -- owner id :: Type array - */ - -function getRecordOwnerId($record) -{ - global $log; - $log->debug("Entering getRecordOwnerId(".$record.") method ..."); - global $adb; - $ownerArr=Array(); - $query="select smownerid from vtiger_crmentity where crmid = ?"; - $result=$adb->pquery($query, array($record)); - if($adb->num_rows($result) > 0) - { - $ownerId=$adb->query_result($result,0,'smownerid'); - $sql_result = $adb->pquery("select count(*) as count from vtiger_users where id = ?",array($ownerId)); - if($adb->query_result($sql_result,0,'count') > 0) - $ownerArr['Users'] = $ownerId; - else - $ownerArr['Groups'] = $ownerId; - } - $log->debug("Exiting getRecordOwnerId method ..."); - return $ownerArr; - -} - -/** Function to insert value to profile2field table - * @param $profileid -- profileid :: Type integer - */ - - -function insertProfile2field($profileid) -{ - global $log; - $log->debug("Entering insertProfile2field(".$profileid.") method ..."); - $log->info("in insertProfile2field ".$profileid); - - global $adb; - $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); - $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); - $num_rows = $adb->num_rows($fld_result); - for($i=0; $i<$num_rows; $i++) { - $tab_id = $adb->query_result($fld_result,$i,'tabid'); - $field_id = $adb->query_result($fld_result,$i,'fieldid'); - $params = array($profileid, $tab_id, $field_id, 0, 0); - $adb->pquery("insert into vtiger_profile2field values (?,?,?,?,?)", $params); - } - $log->debug("Exiting insertProfile2field method ..."); -} - -/** Function to insert into default org field - */ - -function insert_def_org_field() -{ - global $log; - $log->debug("Entering insert_def_org_field() method ..."); - global $adb; - $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); - $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); - $num_rows = $adb->num_rows($fld_result); - for($i=0; $i<$num_rows; $i++) - { - $tab_id = $adb->query_result($fld_result,$i,'tabid'); - $field_id = $adb->query_result($fld_result,$i,'fieldid'); - $params = array($tab_id, $field_id, 0, 0); - $adb->pquery("insert into vtiger_def_org_field values (?,?,?,?)", $params); - } - $log->debug("Exiting insert_def_org_field() method ..."); -} - -/** Function to insert value to profile2field table - * @param $fld_module -- field module :: Type string - * @param $profileid -- profileid :: Type integer - * @returns $result -- result :: Type string - */ - -function getProfile2FieldList($fld_module, $profileid) -{ - global $log; - $log->debug("Entering getProfile2FieldList(".$fld_module.",". $profileid.") method ..."); - $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); - - global $adb; - $tabid = getTabid($fld_module); - - $query = "select vtiger_profile2field.visible,vtiger_field.* from vtiger_profile2field inner join vtiger_field on vtiger_field.fieldid=vtiger_profile2field.fieldid where vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,1,2)"; - $result = $adb->pquery($query, array($profileid, $tabid)); - $log->debug("Exiting getProfile2FieldList method ..."); - return $result; -} - -/** Function to insert value to profile2fieldPermissions table - * @param $fld_module -- field module :: Type string - * @param $profileid -- profileid :: Type integer - * @returns $return_data -- return_data :: Type string - */ - -//added by jeri - -function getProfile2FieldPermissionList($fld_module, $profileid) -{ - global $log; - $log->debug("Entering getProfile2FieldPermissionList(".$fld_module.",". $profileid.") method ..."); - $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); - - // Cache information to re-use - static $_module_fieldpermission_cache = array(); - - if(!isset($_module_fieldpermission_cache[$fld_module])) { - $_module_fieldpermission_cache[$fld_module] = array(); - } - - // Lookup cache first - $return_data = VTCacheUtils::lookupProfile2FieldPermissionList($fld_module, $profileid); - - if($return_data === false) { - - $return_data = array(); - - global $adb; - $tabid = getTabid($fld_module); - - $query = "SELECT vtiger_profile2field.visible, vtiger_profile2field.readonly, vtiger_field.fieldlabel, vtiger_field.uitype, - vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata - FROM vtiger_profile2field INNER JOIN vtiger_field ON vtiger_field.fieldid=vtiger_profile2field.fieldid - WHERE vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,2)"; - - $qparams = array($profileid, $tabid); - $result = $adb->pquery($query, $qparams); - - for($i=0; $i<$adb->num_rows($result); $i++) { - $return_data[]=array( - $adb->query_result($result,$i,"fieldlabel"), - $adb->query_result($result,$i,"visible"), // From vtiger_profile2field.visible - $adb->query_result($result,$i,"uitype"), - $adb->query_result($result,$i,"readonly"), - $adb->query_result($result,$i,"fieldid"), - $adb->query_result($result,$i,"displaytype"), - $adb->query_result($result,$i,"typeofdata") - ); - } - - // Update information to cache for re-use - VTCacheUtils::updateProfile2FieldPermissionList($fld_module, $profileid, $return_data); - } - - - $log->debug("Exiting getProfile2FieldPermissionList method ..."); - return $return_data; -} - - -/** Function to insert value to profile2fieldPermissions table - * @param $fld_module -- field module :: Type string - * @param $profileid -- profileid :: Type integer - * @returns $return_data -- return_data :: Type string - */ - -function getProfile2ModuleFieldPermissionList($fld_module, $profileid) { - global $log; - $log->debug("Entering getProfile2ModuleFieldPermissionList(".$fld_module.",". $profileid.") method ..."); - $log->info("in getProfile2ModuleFieldList ".$fld_module. ' vtiger_profile id is '.$profileid); - - // Cache information to re-use - static $_module_fieldpermission_cache = array(); - - if(!isset($_module_fieldpermission_cache[$fld_module])) { - $_module_fieldpermission_cache[$fld_module] = array(); - } - - $return_data = array(); - - global $adb; - $tabid = getTabid($fld_module); - - $query = "SELECT vtiger_profile2tab.tabid, vtiger_profile2tab.permissions, vtiger_field.fieldlabel, vtiger_field.uitype, - vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata - FROM vtiger_profile2tab INNER JOIN vtiger_field ON vtiger_field.tabid=vtiger_profile2tab.tabid - WHERE vtiger_profile2tab.profileid=? AND vtiger_profile2tab.tabid=? AND vtiger_field.presence in (0,2)"; - $qparams = array($profileid, $tabid); - $result = $adb->pquery($query, $qparams); - - for($i=0; $i<$adb->num_rows($result); $i++) { - $fieldid = $adb->query_result($result,$i,"fieldid"); - $checkentry = $adb->pquery("SELECT 1 FROM vtiger_profile2field WHERE profileid=? AND tabid=? AND fieldid =?",array($profileid,$tabid,$fieldid)); - $visible_value = 0; - $readOnlyValue = 0; - if($adb->num_rows($checkentry) == 0) { - $sql11="INSERT INTO vtiger_profile2field VALUES(?,?,?,?,?)"; - $adb->pquery($sql11, array($profileid, $tabid, $fieldid,$visible_value, $readOnlyValue)); - } - - $sql = "SELECT vtiger_profile2field.visible, vtiger_profile2field.readonly FROM vtiger_profile2field WHERE fieldid=? AND tabid=? AND profileid=?"; - $params = array($fieldid,$tabid,$profileid); - $res = $adb->pquery($sql, $params); - - $return_data[]=array( - $adb->query_result($result,$i,"fieldlabel"), - $adb->query_result($res,0,"visible"), // From vtiger_profile2field.visible - $adb->query_result($result,$i,"uitype"), - $adb->query_result($res,0,"readonly"), // From vtiger_profile2field.readonly - $adb->query_result($result,$i,"fieldid"), - $adb->query_result($result,$i,"displaytype"), - $adb->query_result($result,$i,"typeofdata") - ); - } - - $log->debug("Exiting getProfile2ModuleFieldPermissionList method ..."); - return $return_data; -} - -/** Function to getProfile2allfieldsListinsert value to profile2fieldPermissions table - * @param $mod_array -- mod_array :: Type string - * @param $profileid -- profileid :: Type integer - * @returns $profilelist -- profilelist :: Type string - */ - -function getProfile2AllFieldList($mod_array,$profileid) -{ - global $log; - $log->debug("Entering getProfile2AllFieldList(".$mod_array.",".$profileid.") method ..."); - $log->info("in getProfile2AllFieldList vtiger_profile id is " .$profileid); - - global $adb; - $profilelist=array(); - for($i=0;$idebug("Exiting getProfile2AllFieldList method ..."); - return $profilelist; -} - -/** Function to getdefaultfield organisation list for a given module - * @param $fld_module -- module name :: Type string - * @returns $result -- string :: Type object - */ - -//end of fn added by jeri - -function getDefOrgFieldList($fld_module) -{ - global $log; - $log->debug("Entering getDefOrgFieldList(".$fld_module.") method ..."); - $log->info("in getDefOrgFieldList ".$fld_module); - - global $adb; - $tabid = getTabid($fld_module); - - $query = "select vtiger_def_org_field.visible,vtiger_field.* from vtiger_def_org_field inner join vtiger_field on vtiger_field.fieldid=vtiger_def_org_field.fieldid where vtiger_def_org_field.tabid=? and vtiger_field.presence in (0,2)"; - $qparams = array($tabid); - $result = $adb->pquery($query, $qparams); - $log->debug("Exiting getDefOrgFieldList method ..."); - return $result; -} - -/** Function to getQuickCreate for a given tabid - * @param $tabid -- tab id :: Type string - * @param $actionid -- action id :: Type integer - * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean - */ - -function getQuickCreate($tabid,$actionid) -{ - global $log; - $log->debug("Entering getQuickCreate(".$tabid.",".$actionid.") method ..."); - $module=getTabModuleName($tabid); - $actionname=getActionname($actionid); - $QuickCreateForm= 'true'; - - $perr=isPermitted($module,$actionname); - if($perr == 'no') - { - $QuickCreateForm= 'false'; - } - $log->debug("Exiting getQuickCreate method ..."); - return $QuickCreateForm; - -} - -/** Function to getQuickCreate for a given tabid - * @param $tabid -- tab id :: Type string - * @param $actionid -- action id :: Type integer - * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean - */ - -function ChangeStatus($status,$activityid,$activity_mode='') - { - global $log; - $log->debug("Entering ChangeStatus(".$status.",".$activityid.",".$activity_mode."='') method ..."); - $log->info("in ChangeStatus ".$status. ' vtiger_activityid is '.$activityid); - - global $adb; - if ($activity_mode == 'Task') - { - $query = "Update vtiger_activity set status=? where activityid = ?"; - } - elseif ($activity_mode == 'Events') - { - $query = "Update vtiger_activity set eventstatus=? where activityid = ?"; - } - if($query) { - $adb->pquery($query, array($status, $activityid)); - } - $log->debug("Exiting ChangeStatus method ..."); - } - -/** Function to get unitprice for a given product id - * @param $productid -- product id :: Type integer - * @returns $up -- up :: Type string - */ - -function getUnitPrice($productid, $module='Products') -{ - global $log, $adb; - $log->debug("Entering getUnitPrice($productid,$module) method ..."); - - if($module == 'Services') { - $query = "select unit_price from vtiger_service where serviceid=?"; - } else { - $query = "select unit_price from vtiger_products where productid=?"; - } - $result = $adb->pquery($query, array($productid)); - $unitpice = $adb->query_result($result,0,'unit_price'); - $log->debug("Exiting getUnitPrice method ..."); - return $unitpice; -} - -/** Function to upload product image file - * @param $mode -- mode :: Type string - * @param $id -- id :: Type integer - * @returns $ret_array -- return array:: Type array - */ - -function upload_product_image_file($mode,$id) -{ - global $log; - $log->debug("Entering upload_product_image_file(".$mode.",".$id.") method ..."); - global $root_directory; - $log->debug("Inside upload_product_image_file. The id is ".$id); - $uploaddir = $root_directory ."/test/product/"; - - $file_path_name = $_FILES['imagename']['name']; - if (isset($_REQUEST['imagename_hidden'])) { - $file_name = $_REQUEST['imagename_hidden']; - } else { - //allowed file pathname like UTF-8 Character - $file_name = ltrim(basename(" ".$file_path_name)); // basename($file_path_name); - } - $file_name = $id.'_'.$file_name; - $filetype= $_FILES['imagename']['type']; - $filesize = $_FILES['imagename']['size']; - - $ret_array = Array(); - - if($filesize > 0) - { - - if(move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$file_name)) - { - - $upload_status = "yes"; - $ret_array["status"] = $upload_status; - $ret_array["file_name"] = $file_name; - - - } - else - { - $errorCode = $_FILES['imagename']['error']; - $upload_status = "no"; - $ret_array["status"] = $upload_status; - $ret_array["errorcode"] = $errorCode; - - - } - - } - else - { - $upload_status = "no"; - $ret_array["status"] = $upload_status; - } - $log->debug("Exiting upload_product_image_file method ..."); - return $ret_array; - -} - -/** Function to upload product image file - * @param $id -- id :: Type integer - * @param $deleted_array -- images to be deleted :: Type array - * @returns $imagename -- imagelist:: Type array - */ - -function getProductImageName($id,$deleted_array='') -{ - global $log; - $log->debug("Entering getProductImageName(".$id.",".$deleted_array."='') method ..."); - global $adb; - $image_array=array(); - $query = "select imagename from vtiger_products where productid=?"; - $result = $adb->pquery($query, array($id)); - $image_name = $adb->query_result($result,0,"imagename"); - $image_array=explode("###",$image_name); - $log->debug("Inside getProductImageName. The image_name is ".$image_name); - if($deleted_array!='') - { - $resultant_image = array(); - $resultant_image=array_merge(array_diff($image_array,$deleted_array)); - $imagelists=implode('###',$resultant_image); - $log->debug("Exiting getProductImageName method ..."); - return $imagelists; - } - else - { - $log->debug("Exiting getProductImageName method ..."); - return $image_name; - } -} - -/** Function to get Contact images - * @param $id -- id :: Type integer - * @returns $imagename -- imagename:: Type string - */ - -function getContactImageName($id) -{ - global $log; - $log->debug("Entering getContactImageName(".$id.") method ..."); - global $adb; - $query = "select imagename from vtiger_contactdetails where contactid=?"; - $result = $adb->pquery($query, array($id)); - $image_name = $adb->query_result($result,0,"imagename"); - $log->debug("Inside getContactImageName. The image_name is ".$image_name); - $log->debug("Exiting getContactImageName method ..."); - return $image_name; - -} - -/** Function to update sub total in inventory - * @param $module -- module name :: Type string - * @param $tablename -- tablename :: Type string - * @param $colname -- colname :: Type string - * @param $colname1 -- coluname1 :: Type string - * @param $entid_fld -- entity field :: Type string - * @param $entid -- entid :: Type integer - * @param $prod_total -- totalproduct :: Type integer - */ - -function updateSubTotal($module,$tablename,$colname,$colname1,$entid_fld,$entid,$prod_total) -{ - global $log; - $log->debug("Entering updateSubTotal(".$module.",".$tablename.",".$colname.",".$colname1.",".$entid_fld.",".$entid.",".$prod_total.") method ..."); - global $adb; - //getting the subtotal - $query = "select ".$colname.",".$colname1." from ".$tablename." where ".$entid_fld."=?"; - $result1 = $adb->pquery($query, array($entid)); - $subtot = $adb->query_result($result1,0,$colname); - $subtot_upd = $subtot - $prod_total; - - $gdtot = $adb->query_result($result1,0,$colname1); - $gdtot_upd = $gdtot - $prod_total; - - //updating the subtotal - $sub_query = "update $tablename set $colname=?, $colname1=? where $entid_fld=?"; - $adb->pquery($sub_query, array($subtot_upd, $gdtot_upd, $entid)); - $log->debug("Exiting updateSubTotal method ..."); -} - -/** Function to get Inventory Total - * @param $return_module -- return module :: Type string - * @param $id -- entity id :: Type integer - * @returns $total -- total:: Type integer - */ - -function getInventoryTotal($return_module,$id) -{ - global $log; - $log->debug("Entering getInventoryTotal(".$return_module.",".$id.") method ..."); - global $adb; - if($return_module == "Potentials") - { - $query ="select vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_seproductsrel.* from vtiger_products inner join vtiger_seproductsrel on vtiger_seproductsrel.productid=vtiger_products.productid where crmid=?"; - } - elseif($return_module == "Products") - { - $query="select vtiger_products.productid,vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_crmentity.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and productid=?"; - } - $result = $adb->pquery($query, array($id)); - $num_rows=$adb->num_rows($result); - $total=0; - for($i=1;$i<=$num_rows;$i++) - { - $unitprice=$adb->query_result($result,$i-1,'unit_price'); - $qty=$adb->query_result($result,$i-1,'quantity'); - $listprice=$adb->query_result($result,$i-1,'listprice'); - if($listprice == '') - $listprice = $unitprice; - if($qty =='') - $qty = 1; - $total = $total+($qty*$listprice); - } - $log->debug("Exiting getInventoryTotal method ..."); - return $total; -} - -/** Function to update product quantity - * @param $product_id -- product id :: Type integer - * @param $upd_qty -- quantity :: Type integer - */ - -function updateProductQty($product_id, $upd_qty) -{ - global $log; - $log->debug("Entering updateProductQty(".$product_id.",". $upd_qty.") method ..."); - global $adb; - $query= "update vtiger_products set qtyinstock=? where productid=?"; - $adb->pquery($query, array($upd_qty, $product_id)); - $log->debug("Exiting updateProductQty method ..."); - -} - -/** Function to get account information - * @param $parent_id -- parent id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function get_account_info($parent_id) -{ - global $log; - $log->debug("Entering get_account_info(".$parent_id.") method ..."); - global $adb; - $query = "select related_to from vtiger_potential where potentialid=?"; - $result = $adb->pquery($query, array($parent_id)); - $accountid=$adb->query_result($result,0,'related_to'); - $log->debug("Exiting get_account_info method ..."); - return $accountid; -} - -/** Function to get quick create form fields - * @param $fieldlabel -- field label :: Type string - * @param $uitype -- uitype :: Type integer - * @param $fieldname -- field name :: Type string - * @param $tabid -- tabid :: Type integer - * @returns $return_field -- return field:: Type string - */ - -//for Quickcreate-Form - -function get_quickcreate_form($fieldlabel,$uitype,$fieldname,$tabid) -{ - global $log; - $log->debug("Entering get_quickcreate_form(".$fieldlabel.",".$uitype.",".$fieldname.",".$tabid.") method ..."); - $return_field =''; - switch($uitype) - { - case 1: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 2: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 6: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 11: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 13: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 15: $return_field .=get_textcomboField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 16: $return_field .=get_textcomboField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 17: $return_field .=get_textwebField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 19: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 22: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 23: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 50: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 51: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 55: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 63: $return_field .=get_textdurationField($fieldlabel,$fieldname,$tabid); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - case 71: $return_field .=get_textField($fieldlabel,$fieldname); - $log->debug("Exiting get_quickcreate_form method ..."); - return $return_field; - break; - } -} - -/** Function to get quick create form fields - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @param $tid -- tabid :: Type integer - * @returns $form_field -- return field:: Type string - */ - -function get_textmanField($label,$name,$tid) -{ - global $log; - $log->debug("Entering get_textmanField(".$label.",".$name.",".$tid.") method ..."); - $form_field=''; - if($tid == 9) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textmanField method ..."); - return $form_field; - } - if($tid == 16) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textmanField method ..."); - return $form_field; - } - else - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textmanField method ..."); - return $form_field; - } - -} - -/** Function to get textfield for website field - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @returns $form_field -- return field:: Type string - */ - -function get_textwebField($label,$name) -{ - global $log; - $log->debug("Entering get_textwebField(".$label.",".$name.") method ..."); - - $form_field=''; - $form_field .=''; - $form_field .= $label.':
http://
'; - $form_field .=''; - $log->debug("Exiting get_textwebField method ..."); - return $form_field; - -} - -/** Function to get textfield - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @returns $form_field -- return field:: Type string - */ - -function get_textField($label,$name) -{ - global $log; - $log->debug("Entering get_textField(".$label.",".$name.") method ..."); - $form_field=''; - if($name == "amount") - { - $form_field .=''; - $form_field .= $label.':(U.S Dollar:$)
'; - $form_field .=''; - $log->debug("Exiting get_textField method ..."); - return $form_field; - } - else - { - - $form_field .=''; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textField method ..."); - return $form_field; - } - -} - -/** Function to get account textfield - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @param $tid -- tabid :: Type integer - * @returns $form_field -- return field:: Type string - */ - -function get_textaccField($label,$name,$tid) -{ - global $log; - $log->debug("Entering get_textaccField(".$label.",".$name.",".$tid.") method ..."); - - global $app_strings; - - $form_field=''; - if($tid == 2) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .='
'; - $form_field .=' '; - $log->debug("Exiting get_textaccField method ..."); - return $form_field; - } - else - { - $form_field .=''; - $form_field .= $label.':
'; - $form_field .='
'; - $form_field .=' '; - $log->debug("Exiting get_textaccField method ..."); - return $form_field; - } - -} - -/** Function to get combo field values - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @returns $form_field -- return field:: Type string - */ - -function get_textcomboField($label,$name) -{ - global $log; - $log->debug("Entering get_textcomboField(".$label.",".$name.") method ..."); - $form_field=''; - if($name == "sales_stage") - { - $comboFieldNames = Array('leadsource'=>'leadsource_dom' - ,'opportunity_type'=>'opportunity_type_dom' - ,'sales_stage'=>'sales_stage_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - } - if($name == "productcategory") - { - $comboFieldNames = Array('productcategory'=>'productcategory_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - } - if($name == "ticketpriorities") - { - $comboFieldNames = Array('ticketpriorities'=>'ticketpriorities_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.':
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - } - if($name == "activitytype") - { - $comboFieldNames = Array('activitytype'=>'activitytype_dom', - 'duration_minutes'=>'duration_minutes_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.'
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - - } - if($name == "eventstatus") - { - $comboFieldNames = Array('eventstatus'=>'eventstatus_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.'
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - - - } - if($name == "taskstatus") - { - $comboFieldNames = Array('taskstatus'=>'taskstatus_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - $form_field .=''; - $form_field .= $label.'
'; - $form_field .=''; - $log->debug("Exiting get_textcomboField method ..."); - return $form_field; - } - - - -} - -/** Function to get date field - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @param $tid -- tabid :: Type integer - * @returns $form_field -- return field:: Type string - */ - - -function get_textdateField($label,$name,$tid) -{ - global $log; - $log->debug("Entering get_textdateField(".$label.",".$name.",".$tid.") method ..."); - global $theme; - global $app_strings; - global $current_user; - - $ntc_date_format = $app_strings['NTC_DATE_FORMAT']; - $ntc_time_format = $app_strings['NTC_TIME_FORMAT']; - - $form_field=''; - $default_date_start = date('Y-m-d'); - $default_time_start = date('H:i'); - $dis_value=getNewDisplayDate(); - - if($tid == 2) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .='('.$current_user->date_format.')
'; - $form_field .=' '; - $form_field .=''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - - } - if($tid == 9) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=' '; - $form_field.= ' '; - $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - } - if($tid == 16) - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=' '; - $form_field.= ' '; - $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - } - - else - { - $form_field .=''; - $form_field .= '*'; - $form_field .= $label.':
'; - $form_field .=' '; - $form_field.= ' '; - $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; - $log->debug("Exiting get_textdateField method ..."); - return $form_field; - } - -} - -/** Function to get duration text field in activity - * @param $label -- field label :: Type string - * @param $name -- field name :: Type string - * @param $tid -- tabid :: Type integer - * @returns $form_field -- return field:: Type string - */ - -function get_textdurationField($label,$name,$tid) -{ - global $log; - $log->debug("Entering get_textdurationField(".$label.",".$name.",".$tid.") method ..."); - $form_field=''; - if($tid == 16) - { - - $comboFieldNames = Array('activitytype'=>'activitytype_dom', - 'duration_minutes'=>'duration_minutes_dom'); - $comboFieldArray = getComboArray($comboFieldNames); - - $form_field .=''; - $form_field .= $label.'
'; - $form_field .=' '; - $form_field .='
(hours/minutes)
'; - $log->debug("Exiting get_textdurationField method ..."); - return $form_field; - } -} - -/** Function to get email text field - * @param $module -- module name :: Type name - * @param $id -- entity id :: Type integer - * @returns $hidden -- hidden:: Type string - */ - -//Added to get the parents list as hidden for Emails -- 09-11-2005 -function getEmailParentsList($module,$id,$focus = false) -{ - global $log; - $log->debug("Entering getEmailParentsList(".$module.",".$id.") method ..."); - global $adb; - // If the information is not sent then read it - if($focus === false) { - if($module == 'Contacts') - $focus = new Contacts(); - if($module == 'Leads') - $focus = new Leads(); - - $focus->retrieve_entity_info($id,$module); - } - - $fieldid = 0; - $fieldname = 'email'; - if($focus->column_fields['email'] == '' && $focus->column_fields['yahooid'] != '' ) - $fieldname = 'yahooid'; - elseif($focus->column_fields['email'] == '' && $focus->column_fields['secondaryemail'] != '' ) - $fieldname='secondaryemail'; - $res = $adb->pquery("select * from vtiger_field where tabid = ? and fieldname= ? and vtiger_field.presence in (0,2)", array(getTabid($module), $fieldname)); - $fieldid = $adb->query_result($res,0,'fieldid'); - - $hidden .= ''; - $hidden .= ''; - - $log->debug("Exiting getEmailParentsList method ..."); - return $hidden; -} - -/** This Function returns the current status of the specified Purchase Order. - * The following is the input parameter for the function - * $po_id --> Purchase Order Id, Type:Integer - */ -function getPoStatus($po_id) -{ - global $log; - $log->debug("Entering getPoStatus(".$po_id.") method ..."); - - global $log; - $log->info("in getPoName ".$po_id); - - global $adb; - $sql = "select postatus from vtiger_purchaseorder where purchaseorderid=?"; - $result = $adb->pquery($sql, array($po_id)); - $po_status = $adb->query_result($result,0,"postatus"); - $log->debug("Exiting getPoStatus method ..."); - return $po_status; -} - -/** This Function adds the specified product quantity to the Product Quantity in Stock in the Warehouse - * The following is the input parameter for the function: - * $productId --> ProductId, Type:Integer - * $qty --> Quantity to be added, Type:Integer - */ -function addToProductStock($productId,$qty) -{ - global $log; - $log->debug("Entering addToProductStock(".$productId.",".$qty.") method ..."); - global $adb; - $qtyInStck=getProductQtyInStock($productId); - $updQty=$qtyInStck + $qty; - $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?"; - $adb->pquery($sql, array($updQty, $productId)); - $log->debug("Exiting addToProductStock method ..."); - -} - -/** This Function adds the specified product quantity to the Product Quantity in Demand in the Warehouse - * @param int $productId - ProductId - * @param int $qty - Quantity to be added - */ -function addToProductDemand($productId,$qty) -{ - global $log; - $log->debug("Entering addToProductDemand(".$productId.",".$qty.") method ..."); - global $adb; - $qtyInStck=getProductQtyInDemand($productId); - $updQty=$qtyInStck + $qty; - $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?"; - $adb->pquery($sql, array($updQty, $productId)); - $log->debug("Exiting addToProductDemand method ..."); - -} - -/** This Function subtract the specified product quantity to the Product Quantity in Stock in the Warehouse - * @param int $productId - ProductId - * @param int $qty - Quantity to be subtracted - */ -function deductFromProductStock($productId,$qty) -{ - global $log; - $log->debug("Entering deductFromProductStock(".$productId.",".$qty.") method ..."); - global $adb; - $qtyInStck=getProductQtyInStock($productId); - $updQty=$qtyInStck - $qty; - $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?"; - $adb->pquery($sql, array($updQty, $productId)); - $log->debug("Exiting deductFromProductStock method ..."); - -} - -/** This Function subtract the specified product quantity to the Product Quantity in Demand in the Warehouse - * @param int $productId - ProductId - * @param int $qty - Quantity to be subtract - */ -function deductFromProductDemand($productId,$qty) -{ - global $log; - $log->debug("Entering deductFromProductDemand(".$productId.",".$qty.") method ..."); - global $adb; - $qtyInStck=getProductQtyInDemand($productId); - $updQty=$qtyInStck - $qty; - $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?"; - $adb->pquery($sql, array($updQty, $productId)); - $log->debug("Exiting deductFromProductDemand method ..."); - -} - - -/** This Function returns the current product quantity in stock. - * The following is the input parameter for the function: - * $product_id --> ProductId, Type:Integer - */ -function getProductQtyInStock($product_id) -{ - global $log; - $log->debug("Entering getProductQtyInStock(".$product_id.") method ..."); - global $adb; - $query1 = "select qtyinstock from vtiger_products where productid=?"; - $result=$adb->pquery($query1, array($product_id)); - $qtyinstck= $adb->query_result($result,0,"qtyinstock"); - $log->debug("Exiting getProductQtyInStock method ..."); - return $qtyinstck; - - -} - -/** This Function returns the current product quantity in demand. - * @param int $product_id - ProductId - * @return int $qtyInDemand - Quantity in Demand of a product - */ -function getProductQtyInDemand($product_id) -{ - global $log; - $log->debug("Entering getProductQtyInDemand(".$product_id.") method ..."); - global $adb; - $query1 = "select qtyindemand from vtiger_products where productid=?"; - $result = $adb->pquery($query1, array($product_id)); - $qtyInDemand = $adb->query_result($result,0,"qtyindemand"); - $log->debug("Exiting getProductQtyInDemand method ..."); - return $qtyInDemand; -} - -/** Function to seperate the Date and Time - * This function accepts a sting with date and time and - * returns an array of two elements.The first element - * contains the date and the second one contains the time - */ -function getDateFromDateAndtime($date_time) -{ - global $log; - $log->debug("Entering getDateFromDateAndtime(".$date_time.") method ..."); - $result = explode(" ",$date_time); - $log->debug("Exiting getDateFromDateAndtime method ..."); - return $result; -} - - -/** Function to get header for block in edit/create and detailview - * @param $header_label -- header label :: Type string - * @returns $output -- output:: Type string - */ - -function getBlockTableHeader($header_label) -{ - global $log; - $log->debug("Entering getBlockTableHeader(".$header_label.") method ..."); - global $mod_strings; - $label = $mod_strings[$header_label]; - $output = $label; - $log->debug("Exiting getBlockTableHeader method ..."); - return $output; - -} - - - -/** Function to get the vtiger_table name from 'field' vtiger_table for the input vtiger_field based on the module - * @param : string $module - current module value - * @param : string $fieldname - vtiger_fieldname to which we want the vtiger_tablename - * @return : string $tablename - vtiger_tablename in which $fieldname is a column, which is retrieved from 'field' vtiger_table per $module basis - */ -function getTableNameForField($module,$fieldname) -{ - global $log; - $log->debug("Entering getTableNameForField(".$module.",".$fieldname.") method ..."); - global $adb; - $tabid = getTabid($module); - //Asha - if($module == 'Calendar') { - $tabid = array('9','16'); - } - $sql = "select tablename from vtiger_field where tabid in (". generateQuestionMarks($tabid) .") and vtiger_field.presence in (0,2) and columnname like ?"; - $res = $adb->pquery($sql, array($tabid, '%'.$fieldname.'%')); - - $tablename = ''; - if($adb->num_rows($res) > 0) - { - $tablename = $adb->query_result($res,0,'tablename'); - } - - $log->debug("Exiting getTableNameForField method ..."); - return $tablename; -} - -/** Function to get parent record owner - * @param $tabid -- tabid :: Type integer - * @param $parModId -- parent module id :: Type integer - * @param $record_id -- record id :: Type integer - * @returns $parentRecOwner -- parentRecOwner:: Type integer - */ - -function getParentRecordOwner($tabid,$parModId,$record_id) -{ - global $log; - $log->debug("Entering getParentRecordOwner(".$tabid.",".$parModId.",".$record_id.") method ..."); - $parentRecOwner=Array(); - $parentTabName=getTabname($parModId); - $relTabName=getTabname($tabid); - $fn_name="get".$relTabName."Related".$parentTabName; - $ent_id=$fn_name($record_id); - if($ent_id != '') - { - $parentRecOwner=getRecordOwnerId($ent_id); - } - $log->debug("Exiting getParentRecordOwner method ..."); - return $parentRecOwner; -} - -/** Function to get potential related accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getPotentialsRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getPotentialsRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select related_to from vtiger_potential where potentialid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'related_to'); - $log->debug("Exiting getPotentialsRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get email related accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ -function getEmailsRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getEmailsRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Accounts' and activityid=?"; - $result = $adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'crmid'); - $log->debug("Exiting getEmailsRelatedAccounts method ..."); - return $accountid; -} -/** Function to get email related Leads - * @param $record_id -- record id :: Type integer - * @returns $leadid -- leadid:: Type integer - */ - -function getEmailsRelatedLeads($record_id) -{ - global $log; - $log->debug("Entering getEmailsRelatedLeads(".$record_id.") method ..."); - global $adb; - $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Leads' and activityid=?"; - $result = $adb->pquery($query, array($record_id)); - $leadid=$adb->query_result($result,0,'crmid'); - $log->debug("Exiting getEmailsRelatedLeads method ..."); - return $leadid; -} - -/** Function to get HelpDesk related Accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getHelpDeskRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getHelpDeskRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select parent_id from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.parent_id where ticketid=? and vtiger_crmentity.setype='Accounts'"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'parent_id'); - $log->debug("Exiting getHelpDeskRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get Quotes related Accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getQuotesRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getQuotesRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select accountid from vtiger_quotes where quoteid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'accountid'); - $log->debug("Exiting getQuotesRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get Quotes related Potentials - * @param $record_id -- record id :: Type integer - * @returns $potid -- potid:: Type integer - */ - -function getQuotesRelatedPotentials($record_id) -{ - global $log; - $log->debug("Entering getQuotesRelatedPotentials(".$record_id.") method ..."); - global $adb; - $query="select potentialid from vtiger_quotes where quoteid=?"; - $result=$adb->pquery($query, array($record_id)); - $potid=$adb->query_result($result,0,'potentialid'); - $log->debug("Exiting getQuotesRelatedPotentials method ..."); - return $potid; -} - -/** Function to get Quotes related Potentials - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getSalesOrderRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getSalesOrderRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select accountid from vtiger_salesorder where salesorderid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'accountid'); - $log->debug("Exiting getSalesOrderRelatedAccounts method ..."); - return $accountid; -} - -/** Function to get SalesOrder related Potentials - * @param $record_id -- record id :: Type integer - * @returns $potid -- potid:: Type integer - */ - -function getSalesOrderRelatedPotentials($record_id) -{ - global $log; - $log->debug("Entering getSalesOrderRelatedPotentials(".$record_id.") method ..."); - global $adb; - $query="select potentialid from vtiger_salesorder where salesorderid=?"; - $result=$adb->pquery($query, array($record_id)); - $potid=$adb->query_result($result,0,'potentialid'); - $log->debug("Exiting getSalesOrderRelatedPotentials method ..."); - return $potid; -} -/** Function to get SalesOrder related Quotes - * @param $record_id -- record id :: Type integer - * @returns $qtid -- qtid:: Type integer - */ - -function getSalesOrderRelatedQuotes($record_id) -{ - global $log; - $log->debug("Entering getSalesOrderRelatedQuotes(".$record_id.") method ..."); - global $adb; - $query="select quoteid from vtiger_salesorder where salesorderid=?"; - $result=$adb->pquery($query, array($record_id)); - $qtid=$adb->query_result($result,0,'quoteid'); - $log->debug("Exiting getSalesOrderRelatedQuotes method ..."); - return $qtid; -} - -/** Function to get Invoice related Accounts - * @param $record_id -- record id :: Type integer - * @returns $accountid -- accountid:: Type integer - */ - -function getInvoiceRelatedAccounts($record_id) -{ - global $log; - $log->debug("Entering getInvoiceRelatedAccounts(".$record_id.") method ..."); - global $adb; - $query="select accountid from vtiger_invoice where invoiceid=?"; - $result=$adb->pquery($query, array($record_id)); - $accountid=$adb->query_result($result,0,'accountid'); - $log->debug("Exiting getInvoiceRelatedAccounts method ..."); - return $accountid; -} -/** Function to get Invoice related SalesOrder - * @param $record_id -- record id :: Type integer - * @returns $soid -- soid:: Type integer - */ - -function getInvoiceRelatedSalesOrder($record_id) -{ - global $log; - $log->debug("Entering getInvoiceRelatedSalesOrder(".$record_id.") method ..."); - global $adb; - $query="select salesorderid from vtiger_invoice where invoiceid=?"; - $result=$adb->pquery($query, array($record_id)); - $soid=$adb->query_result($result,0,'salesorderid'); - $log->debug("Exiting getInvoiceRelatedSalesOrder method ..."); - return $soid; -} - - -/** Function to get Days and Dates in between the dates specified - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function get_days_n_dates($st,$en) -{ - global $log; - $log->debug("Entering get_days_n_dates(".$st.",".$en.") method ..."); - $stdate_arr=explode("-",$st); - $endate_arr=explode("-",$en); - - $dateDiff = mktime(0,0,0,$endate_arr[1],$endate_arr[2],$endate_arr[0]) - mktime(0,0,0,$stdate_arr[1],$stdate_arr[2],$stdate_arr[0]);//to get dates difference - - $days = floor($dateDiff/60/60/24)+1; //to calculate no of. days - for($i=0;$i<$days;$i++) - { - $day_date[] = date("Y-m-d",mktime(0,0,0,date("$stdate_arr[1]"),(date("$stdate_arr[2]")+($i)),date("$stdate_arr[0]"))); - } - if(!isset($day_date)) - $day_date=0; - $nodays_dates=array($days,$day_date); - $log->debug("Exiting get_days_n_dates method ..."); - return $nodays_dates; //passing no of days , days in between the days -}//function end - - -/** Function to get the start and End Dates based upon the period which we give - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function start_end_dates($period) -{ - global $log; - $log->debug("Entering start_end_dates(".$period.") method ..."); - $st_thisweek= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y"))); - if($period=="tweek") - { - $st_date= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y"))); - $end_date = date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-1),date("Y"))); - $st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y"))); - if($st_week==0) - { - $start_week=explode("-",$st_thisweek); - $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]"))); - $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]"))); - } - $period_type="week"; - $width="360"; - } - else if($period=="lweek") - { - $start_week=explode("-",$st_thisweek); - $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]"))); - $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]"))); - $st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y"))); - if($st_week==0) - { - $start_week=explode("-",$st_thisweek); - $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-14),date("$start_week[0]"))); - $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-8),date("$start_week[0]"))); - } - $period_type="week"; - $width="360"; - } - else if($period=="tmon") - { - $period_type="month"; - $width="840"; - $st_date = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y"))); - $end_date = date("Y-m-t"); - - } - else if($period=="lmon") - { - $st_date=date("Y-m-d",mktime(0,0,0,date("n")-1,date("1"),date("Y"))); - $end_date = date("Y-m-d",mktime(0, 0, 1, date("n"), 0,date("Y"))); - $period_type="month"; - $start_month=date("d",mktime(0,0,0,date("n"),date("j"),date("Y"))); - if($start_month==1) - { - $st_date=date("Y-m-d",mktime(0,0,0,date("n")-2,date("1"),date("Y"))); - $end_date = date("Y-m-d",mktime(0, 0, 1, date("n")-1, 0,date("Y"))); - } - - $width="840"; - } - else - { - $curr_date=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y"))); - $today_date=explode("-",$curr_date); - $lastday_date=date("Y-m-d",mktime(0,0,0,date("$today_date[1]"),date("$today_date[2]")-1,date("$today_date[0]"))); - $st_date=$lastday_date; - $end_date=$lastday_date; - $period_type="yday"; - $width="250"; - } - if($period_type=="yday") - $height="160"; - else - $height="250"; - $datevalues=array($st_date,$end_date,$period_type,$width,$height); - $log->debug("Exiting start_end_dates method ..."); - return $datevalues; -}//function ends - - -/** Function to get the Graph and vtiger_table format for a particular date - based upon the period - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function Graph_n_table_format($period_type,$date_value) -{ - global $log; - $log->debug("Entering Graph_n_table_format(".$period_type.",".$date_value.") method ..."); - $date_val=explode("-",$date_value); - if($period_type=="month") //to get the vtiger_table format dates - { - $table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); - $graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); - } - else if($period_type=="week") - { - $table_format=date("d/m",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); - $graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); - } - else if($period_type=="yday") - { - $table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); - $graph_format=$table_format; - } - $values=array($graph_format,$table_format); - $log->debug("Exiting Graph_n_table_format method ..."); - return $values; -} - -/** Function to get image count for a given product - * @param $id -- product id :: Type integer - * @returns count -- count:: Type integer - */ - -function getImageCount($id) -{ - global $log; - $log->debug("Entering getImageCount(".$id.") method ..."); - global $adb; - $image_lists=array(); - $query="select imagename from vtiger_products where productid=?"; - $result=$adb->pquery($query, array($id)); - $imagename=$adb->query_result($result,0,'imagename'); - $image_lists=explode("###",$imagename); - $log->debug("Exiting getImageCount method ..."); - return count($image_lists); - -} - -/** Function to get user image for a given user - * @param $id -- user id :: Type integer - * @returns $image_name -- image name:: Type string - */ - -function getUserImageName($id) -{ - global $log; - $log->debug("Entering getUserImageName(".$id.") method ..."); - global $adb; - $query = "select imagename from vtiger_users where id=?"; - $result = $adb->pquery($query, array($id)); - $image_name = $adb->query_result($result,0,"imagename"); - $log->debug("Inside getUserImageName. The image_name is ".$image_name); - $log->debug("Exiting getUserImageName method ..."); - return $image_name; - -} - -/** Function to get all user images for displaying it in listview - * @returns $image_name -- image name:: Type array - */ - -function getUserImageNames() -{ - global $log; - $log->debug("Entering getUserImageNames() method ..."); - global $adb; - $query = "select imagename from vtiger_users where deleted=0"; - $result = $adb->pquery($query, array()); - $image_name=array(); - for($i=0;$i<$adb->num_rows($result);$i++) - { - if($adb->query_result($result,$i,"imagename")!='') - $image_name[] = $adb->query_result($result,$i,"imagename"); - } - $log->debug("Inside getUserImageNames."); - if(count($image_name) > 0) - { - $log->debug("Exiting getUserImageNames method ..."); - return $image_name; - } -} - -/** Function to remove the script tag in the contents - * Portions created by vtiger are Copyright (C) vtiger. - * All Rights Reserved. - * Contributor(s): ______________________________________.. - */ -function strip_selected_tags($text, $tags = array()) -{ - $args = func_get_args(); - $text = array_shift($args); - $tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags; - foreach ($tags as $tag){ - if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){ - $text = str_replace($found[0],$found[1],$text); - } - } - - return $text; -} - -/** Function to check whether user has opted for internal mailer - * @returns $int_mailer -- int mailer:: Type boolean - */ -function useInternalMailer() { - global $current_user,$adb; - return $adb->query_result($adb->pquery("select int_mailer from vtiger_mail_accounts where user_id=?", array($current_user->id)),0,"int_mailer"); -} - -/** -* the function is like unescape in javascript -* added by dingjianting on 2006-10-1 for picklist editor -*/ -function utf8RawUrlDecode ($source) { - global $default_charset; - $decodedStr = ""; - $pos = 0; - $len = strlen ($source); - while ($pos < $len) { - $charAt = substr ($source, $pos, 1); - if ($charAt == '%') { - $pos++; - $charAt = substr ($source, $pos, 1); - if ($charAt == 'u') { - // we got a unicode character - $pos++; - $unicodeHexVal = substr ($source, $pos, 4); - $unicode = hexdec ($unicodeHexVal); - $entity = "&#". $unicode . ';'; - $decodedStr .= utf8_encode ($entity); - $pos += 4; - } - else { - // we have an escaped ascii character - $hexVal = substr ($source, $pos, 2); - $decodedStr .= chr (hexdec ($hexVal)); - $pos += 2; - } - } else { - $decodedStr .= $charAt; - $pos++; - } - } - if(strtolower($default_charset) == 'utf-8') - return html_to_utf8($decodedStr); - else - return $decodedStr; - //return html_to_utf8($decodedStr); -} - -/** -*simple HTML to UTF-8 conversion: -*/ -function html_to_utf8 ($data) -{ - return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data); -} - -function _html_to_utf8 ($data) -{ - if ($data > 127) - { - $i = 5; - while (($i--) > 0) - { - if ($data != ($a = $data % ($p = pow(64, $i)))) - { - $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p)); - for ($i; $i > 0; $i--) - $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p)); - break; - } - } - } - else - $ret = "&#$data;"; - return $ret; -} - -// Return Question mark -function _questionify($v){ - return "?"; -} - -/** -* Function to generate question marks for a given list of items -*/ -function generateQuestionMarks($items_list) { - // array_map will call the function specified in the first parameter for every element of the list in second parameter - if (is_array($items_list)) { - return implode(",", array_map("_questionify", $items_list)); - } else { - return implode(",", array_map("_questionify", explode(",", $items_list))); - } -} - -/** -* Function to find the UI type of a field based on the uitype id -*/ -function is_uitype($uitype, $reqtype) { - $ui_type_arr = array( - '_date_' => array(5, 6, 23, 70), - '_picklist_' => array(15, 16, 52, 53, 54, 55, 59, 62, 63, 66, 68, 76, 77, 78, 80, 98, 101, 115, 357), - '_users_list_' => array(52), - ); - - if ($ui_type_arr[$reqtype] != null) { - if (in_array($uitype, $ui_type_arr[$reqtype])) { - return true; - } - } - return false; -} -/** - * Function to escape quotes - * @param $value - String in which single quotes have to be replaced. - * @return Input string with single quotes escaped. - */ -function escape_single_quotes($value) { - if (isset($value)) $value = str_replace("'", "\'", $value); - return $value; -} - -/** - * Function to format the input value for SQL like clause. - * @param $str - Input string value to be formatted. - * @param $flag - By default set to 0 (Will look for cases %string%). - * If set to 1 - Will look for cases %string. - * If set to 2 - Will look for cases string%. - * @return String formatted as per the SQL like clause requirement - */ -function formatForSqlLike($str, $flag=0,$is_field=false) { - global $adb; - if (isset($str)) { - if($is_field==false){ - $str = str_replace('%', '\%', $str); - $str = str_replace('_', '\_', $str); - if ($flag == 0) { - $str = '%'. $str .'%'; - } elseif ($flag == 1) { - $str = '%'. $str; - } elseif ($flag == 2) { - $str = $str .'%'; - } - } else { - if ($flag == 0) { - $str = 'concat("%",'. $str .',"%")'; - } elseif ($flag == 1) { - $str = 'concat("%",'. $str .')'; - } elseif ($flag == 2) { - $str = 'concat('. $str .',"%")'; - } - } - } - return $adb->sql_escape_string($str); -} - -/** - * Get Current Module (global variable or from request) - */ -function getCurrentModule($perform_set=false) { - global $currentModule,$root_directory; - if(isset($currentModule)) return $currentModule; - - // Do some security check and return the module information - if(isset($_REQUEST['module'])) - { - $is_module = false; - $module = $_REQUEST['module']; - $dir = @scandir($root_directory."modules"); - $temp_arr = Array("CVS","Attic"); - $res_arr = @array_intersect($dir,$temp_arr); - if(count($res_arr) == 0 && !preg_match("/[\/.]/",$module)) { - if(@in_array($module,$dir)) - $is_module = true; - } - - if($is_module) { - if($perform_set) $currentModule = $module; - return $module; - } - } - return null; -} - - -/** - * Set the language strings. - */ -function setCurrentLanguage($active_module=null) { - global $current_language, $default_language, $app_strings, $app_list_strings, $mod_strings, $currentModule; - - if($active_module==null) { - if (!isset($currentModule)) - $active_module = getCurrentModule(); - else - $active_module = $currentModule; - } - - if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') - { - $current_language = $_SESSION['authenticated_user_language']; - } - else - { - $current_language = $default_language; - } - - //set module and application string arrays based upon selected language - if (!isset($app_strings)) - $app_strings = return_application_language($current_language); - if (!isset($app_list_strings)) - $app_list_strings = return_app_list_strings_language($current_language); - if (!isset($mod_strings) && isset($active_module)) - $mod_strings = return_module_language($current_language, $active_module); -} - -/** Function used to get all the picklists and their values for a module - @param string $module - Module name to which the list of picklists and their values needed - @return array $fieldlists - Array of picklists and their values -**/ -function getAccessPickListValues($module) -{ - global $adb, $log; - global $current_user; - $log->debug("Entering into function getAccessPickListValues($module)"); - - $id = getTabid($module); - $query = "select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from vtiger_field where tabid = ? and uitype in ('15','33','55') and vtiger_field.presence in (0,2)"; - $result = $adb->pquery($query, array($id)); - - $roleid = $current_user->roleid; - $subrole = getRoleSubordinates($roleid); - - if(count($subrole)> 0) - { - $roleids = $subrole; - array_push($roleids, $roleid); - } - else - { - $roleids = $roleid; - } - - $temp_status = Array(); - for($i=0;$i < $adb->num_rows($result);$i++) - { - $fieldname = $adb->query_result($result,$i,"fieldname"); - $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); - $columnname = $adb->query_result($result,$i,"columnname"); - $tabid = $adb->query_result($result,$i,"tabid"); - $uitype = $adb->query_result($result,$i,"uitype"); - - $keyvalue = $columnname; - $fieldvalues = Array(); - if (count($roleids) > 1) - { - $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\") and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; - } - else - { - $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid ='".$roleid."' and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; - } - if($fieldname != 'firstname') - $mulselresult = $adb->query($mulsel); - for($j=0;$j < $adb->num_rows($mulselresult);$j++) - { - $fieldvalues[] = $adb->query_result($mulselresult,$j,$fieldname); - } - $field_count = count($fieldvalues); - if($uitype == 15 && $field_count > 0 && ($fieldname == 'taskstatus' || $fieldname == 'eventstatus')) - { - $temp_count =count($temp_status[$keyvalue]); - if($temp_count > 0) - { - for($t=0;$t < $field_count;$t++) - { - $temp_status[$keyvalue][($temp_count+$t)] = $fieldvalues[$t]; - } - $fieldvalues = $temp_status[$keyvalue]; - } - else - $temp_status[$keyvalue] = $fieldvalues; - } - if($uitype == 33) - $fieldlists[1][$keyvalue] = $fieldvalues; - else if($uitype == 55 && $fieldname == 'salutationtype') - $fieldlists[$keyvalue] = $fieldvalues; - else if($uitype == 15) - $fieldlists[$keyvalue] = $fieldvalues; - } - $log->debug("Exit from function getAccessPickListValues($module)"); - - return $fieldlists; -} - -function get_config_status() { - global $default_charset; - if(strtolower($default_charset) == 'utf-8') - $config_status=1; - else - $config_status=0; - return $config_status; -} - -function getMigrationCharsetFlag() { - global $adb; - - if(!$adb->isPostgres()) - $db_status=check_db_utf8_support($adb); - $config_status=get_config_status(); - - if ($db_status == $config_status) { - if ($db_status == 1) { // Both are UTF-8 - $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_UTF8; - } else { // Both are Non UTF-8 - $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8; - } - } else { - if ($db_status == 1) { // Database charset is UTF-8 and CRM charset is Non UTF-8 - $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_UTF8; - } else { // Database charset is Non UTF-8 and CRM charset is UTF-8 - $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_NONUTF8; - } - } - return $db_migration_status; -} - -/** Function to convert a given time string to Minutes */ -function ConvertToMinutes($time_string) -{ - $interval = split(' ', $time_string); - $interval_minutes = intval($interval[0]); - $interval_string = strtolower($interval[1]); - if($interval_string == 'hour' || $interval_string == 'hours') - { - $interval_minutes = $interval_minutes * 60; - } - elseif($interval_string == 'day' || $interval_string == 'days') - { - $interval_minutes = $interval_minutes * 1440; - } - return $interval_minutes; -} - -//added to find duplicates -/** To get the converted record values which have to be display in duplicates merging tpl*/ -function getRecordValues($id_array,$module) { - global $adb,$current_user; - global $app_strings; - $tabid=getTabid($module); - $query="select fieldname,fieldlabel,uitype from vtiger_field where tabid=? and fieldname not in ('createdtime','modifiedtime') and vtiger_field.presence in (0,2) and uitype not in('4')"; - $result=$adb->pquery($query, array($tabid)); - $no_rows=$adb->num_rows($result); - - $focus = new $module(); - if(isset($id_array) && $id_array !='') { - foreach($id_array as $value_pair['disp_value']) { - $focus->id=$value_pair['disp_value']; - $focus->retrieve_entity_info($value_pair['disp_value'],$module); - $field_values[]=$focus->column_fields; - } - } - - $labl_array=array(); - $value_pair = array(); - $c = 0; - for($i=0;$i<$no_rows;$i++) { - $fld_name=$adb->query_result($result,$i,"fieldname"); - $fld_label=$adb->query_result($result,$i,"fieldlabel"); - $ui_type=$adb->query_result($result,$i,"uitype"); - - if(getFieldVisibilityPermission($module,$current_user->id,$fld_name, 'readwrite') == '0') { - $fld_array []= $fld_name; - $record_values[$c][$fld_label] = Array(); - $ui_value[]=$ui_type; - for($j=0;$j < count($field_values);$j++) { - - if($ui_type ==56) { - if($field_values[$j][$fld_name] == 0) - $value_pair['disp_value']=$app_strings['no']; - else - $value_pair['disp_value']=$app_strings['yes']; - } elseif($ui_type == 51 || $ui_type == 50) { - $entity_id=$field_values[$j][$fld_name]; - if($module !='Products') - $entity_name=getAccountName($entity_id); - else - $entity_name=getProductName($entity_id); - $value_pair['disp_value']=$entity_name; - } elseif($ui_type == 53) { - $owner_id=$field_values[$j][$fld_name]; - $ownername=getOwnerName($owner_id); - $value_pair['disp_value']=$ownername; - } elseif($ui_type ==57) { - $contact_id= $field_values[$j][$fld_name]; - if($contact_id != '') { - $displayValueArray = getEntityName('Contacts', $contact_id); - if (!empty($displayValueArray)) { - foreach ($displayValueArray as $key => $field_value) { - $contactname = $field_value; - } - } - } - $value_pair['disp_value']=$contactname; - } elseif($ui_type == 75 || $ui_type ==81) { - $vendor_id=$field_values[$j][$fld_name]; - if($vendor_id != '') { - $vendor_name=getVendorName($vendor_id); - } - $value_pair['disp_value']=$vendor_name; - } elseif($ui_type == 52) { - $user_id = $field_values[$j][$fld_name]; - $user_name=getUserFullName($user_id); - $value_pair['disp_value']=$user_name; - } elseif($ui_type ==68) { - $parent_id = $field_values[$j][$fld_name]; - $value_pair['disp_value'] = getAccountName($parent_id); - if($value_pair['disp_value'] == '' || $value_pair['disp_value'] == NULL) { - $displayValueArray = getEntityName('Contacts', $parent_id); - if (!empty($displayValueArray)) { - foreach ($displayValueArray as $key => $field_value) { - $contact_name = $field_value; - } - } else { - $contact_name=''; - } - $value_pair['disp_value'] = $contact_name; - } - } elseif($ui_type ==59) { - $product_name=getProductName($field_values[$j][$fld_name]); - if($product_name != '') - $value_pair['disp_value']=$product_name; - else $value_pair['disp_value']=''; - } elseif($ui_type==58) { - $campaign_name=getCampaignName($field_values[$j][$fld_name]); - if($campaign_name != '') - $value_pair['disp_value']=$campaign_name; - else $value_pair['disp_value']=''; - } elseif($ui_type == 10) { - $value_pair['disp_value'] = getRecordInfoFromID($field_values[$j][$fld_name]); - }elseif($ui_type == 5 || $ui_type == 6 || $ui_type == 23){ - if ($field_values[$j][$fld_name] != '' && $field_values[$j][$fld_name] - != '0000-00-00') { - $date = new DateTimeField($field_values[$j][$fld_name]); - $value_pair['disp_value'] = $date->getDisplayDate(); - if(strpos($field_values[$j][$fld_name], ' ') > -1) { - $value_pair['disp_value'] .= (' ' . $date->getDisplayTime()); - } - } elseif ($field_values[$j][$fld_name] == '0000-00-00') { - $value_pair['disp_value'] = ''; - } else { - $value_pair['disp_value'] = $field_values[$j][$fld_name]; - } - }elseif($ui_type == '71' || $ui_type == '72') { - $currencyField = new CurrencyField($field_values[$j][$fld_name]); - if($ui_type == '72') { - $value_pair['disp_value'] = $currencyField->getDisplayValue(null, true); - } else { - $value_pair['disp_value'] = $currencyField->getDisplayValue(); - } - } else { - $value_pair['disp_value']=$field_values[$j][$fld_name]; - } - $value_pair['org_value'] = $field_values[$j][$fld_name]; - - array_push($record_values[$c][$fld_label],$value_pair); - } - $c++; - } - - } - $parent_array[0]=$record_values; - $parent_array[1]=$fld_array; - $parent_array[2]=$fld_array; - return $parent_array; -} - -/** Function to check whether the relationship entries are exist or not on elationship tables */ -function is_related($relation_table,$crm_field,$related_module_id,$crmid) -{ - global $adb; - $check_res = $adb->query("select * from $relation_table where $crm_field=$related_module_id and crmid=$crmid"); - $count = $adb->num_rows($check_res); - if($count > 0) - return true; - else - return false; -} - -/** Function to get a to find duplicates in a particular module*/ -function getDuplicateQuery($module,$field_values,$ui_type_arr) -{ - global $current_user; - $tbl_col_fld = explode(",", $field_values); - $i=0; - foreach($tbl_col_fld as $val) { - list($tbl[$i], $cols[$i], $fields[$i]) = explode(".", $val); - $tbl_cols[$i] = $tbl[$i]. "." . $cols[$i]; - $i++; - } - $table_cols = implode(",",$tbl_cols); - $sec_parameter = getSecParameterforMerge($module); - - if($module == 'Contacts') - { - $nquery = "SELECT vtiger_contactdetails.contactid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_contactdetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid - INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid - INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid - LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid - LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid - LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (SELECT $table_cols - FROM vtiger_contactdetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid - INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid - INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid - LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid - LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_contactdetails.contactid ASC"; - - } - else if($module == 'Accounts') - { - $nquery="SELECT vtiger_account.accountid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_account - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid - INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid - INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid - LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_account.accountid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (SELECT $table_cols - FROM vtiger_account - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid - INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid - INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid - LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_account.accountid ASC"; - } - else if($module == 'Leads') - { - $nquery = "SELECT vtiger_leaddetails.leadid AS recordid, vtiger_users_last_import.deleted,$table_cols - FROM vtiger_leaddetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid - INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid - INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid - LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_leaddetails.leadid - INNER JOIN (SELECT $table_cols - FROM vtiger_leaddetails - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid - INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid - INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid - LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter - GROUP BY $table_cols HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter ORDER BY $table_cols,vtiger_leaddetails.leadid ASC"; - - } - else if($module == 'Products') - { - $nquery = "SELECT vtiger_products.productid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_products - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_products.productid - LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (SELECT $table_cols - FROM vtiger_products - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid - LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_products.productid ASC"; - } - else if($module == "HelpDesk") - { - $nquery = "SELECT vtiger_troubletickets.ticketid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_troubletickets - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_troubletickets.ticketid - LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_troubletickets.ticketid - LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id - LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid - INNER JOIN (SELECT $table_cols FROM vtiger_troubletickets - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid - LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid - LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id - LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_contactdetails contd ON contd.contactid = vtiger_troubletickets.parent_id - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_troubletickets.ticketid ASC"; - } - else if($module == "Potentials") - { - $nquery = "SELECT vtiger_potential.potentialid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_potential - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_potential.potentialid - LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_potential.potentialid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - INNER JOIN (SELECT $table_cols - FROM vtiger_potential - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_potential.potentialid - LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid - LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid - LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid - WHERE vtiger_crmentity.deleted=0 $sec_parameter - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_potential.potentialid ASC"; - } - else if($module == "Vendors") - { - $nquery = "SELECT vtiger_vendor.vendorid AS recordid, - vtiger_users_last_import.deleted,".$table_cols." - FROM vtiger_vendor - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_vendor.vendorid - LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid - LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_vendor.vendorid - INNER JOIN (SELECT $table_cols - FROM vtiger_vendor - INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_vendor.vendorid - LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid - WHERE vtiger_crmentity.deleted=0 - GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp - ON ".get_on_clause($field_values,$ui_type_arr,$module) ." - WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_vendor.vendorid ASC"; - } else { - $modObj = CRMEntity::getInstance($module); - if ($modObj != null && method_exists($modObj, 'getDuplicatesQuery')) { - $nquery = $modObj->getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr); - } - } - return $nquery; -} - -/** Function to return the duplicate records data as a formatted array */ -function getDuplicateRecordsArr($module) -{ - global $adb,$app_strings,$list_max_entries_per_page,$theme; - $field_values_array=getFieldValues($module); - $field_values=$field_values_array['fieldnames_list']; - $fld_arr=$field_values_array['fieldnames_array']; - $col_arr=$field_values_array['columnnames_array']; - $fld_labl_arr=$field_values_array['fieldlabels_array']; - $ui_type=$field_values_array['fieldname_uitype']; - - $dup_query = getDuplicateQuery($module,$field_values,$ui_type); - // added for page navigation - $dup_count_query = substr($dup_query, stripos($dup_query,'FROM'),strlen($dup_query)); - $dup_count_query = "SELECT count(*) as count ".$dup_count_query; - $count_res = $adb->query($dup_count_query); - $no_of_rows = $adb->query_result($count_res,0,"count"); - - if($no_of_rows <= $list_max_entries_per_page) - $_SESSION['dup_nav_start'.$module] = 1; - else if(isset($_REQUEST["start"]) && $_REQUEST["start"] != "" && $_SESSION['dup_nav_start'.$module] != $_REQUEST["start"]) - $_SESSION['dup_nav_start'.$module] = ListViewSession::getRequestStartPage(); - $start = ($_SESSION['dup_nav_start'.$module] != "")?$_SESSION['dup_nav_start'.$module]:1; - $navigation_array = getNavigationValues($start, $no_of_rows, $list_max_entries_per_page); - $start_rec = $navigation_array['start']; - $end_rec = $navigation_array['end_val']; - $navigationOutput = getTableHeaderNavigation($navigation_array, "",$module,"FindDuplicate",""); - if ($start_rec == 0) - $limit_start_rec = 0; - else - $limit_start_rec = $start_rec -1; - $dup_query .= " LIMIT $limit_start_rec, $list_max_entries_per_page"; - //ends - - $nresult=$adb->query($dup_query); - $no_rows=$adb->num_rows($nresult); - require_once('modules/Vtiger/layout_utils.php'); - if($no_rows == 0) - { - if ($_REQUEST['action'] == 'FindDuplicateRecords') - { - //echo "

".$app_strings['LBL_NO_DUPLICATE']." ".$app_strings['LBL_GO_BACK'].".
"; - //die; - echo ""; - echo "
"; - echo "
- - - - - - - - - -
$app_strings[LBL_NO_DUPLICATE]
- $app_strings[LBL_GO_BACK]
-
"; - echo "
"; - exit(); - } - else - { - echo "

".$app_strings['LBL_NO_DUPLICATE']."
"; - die; - } - } - - $rec_cnt = 0; - $temp = Array(); - $sl_arr = Array(); - $grp = "group0"; - $gcnt = 0; - $ii = 0; //ii'th record in group - while ( $rec_cnt < $no_rows ) - { - $result = $adb->fetchByAssoc($nresult); - //echo '
';print_r($result);echo '
'; - if($rec_cnt != 0) - { - $sl_arr = array_slice($result,2); - array_walk($temp,'lower_array'); - array_walk($sl_arr,'lower_array'); - $arr_diff = array_diff($temp,$sl_arr); - if(count($arr_diff) > 0) - { - $gcnt++; - $temp = $sl_arr; - $ii = 0; - } - $grp = "group".$gcnt; - } - $fld_values[$grp][$ii]['recordid'] = $result['recordid']; - for($k=0;$k $field_value) { - $contactname = $field_value; - } - } - } - - $result[$col_arr[$k]]=$contactname; - } - if($ui_type[$fld_arr[$k]] == 15 || $ui_type[$fld_arr[$k]] == 16) - { - $result[$col_arr[$k]]=getTranslatedString($result[$col_arr[$k]],$module); - } - if($ui_type[$fld_arr[$k]] == 33){ - $fieldvalue = explode(' |##| ',$result[$col_arr[$k]]); - $result[$col_arr[$k]] = array(); - foreach ($fieldvalue as $picklistValue) { - $result[$col_arr[$k]][] = getTranslatedString($picklistValue,$module); - } - $result[$col_arr[$k]] = implode(', ',$result[$col_arr[$k]]); - } - if($ui_type[$fld_arr[$k]] ==68) - { - $parent_id= $result[$col_arr[$k]]; - if($parent_id != '') - { - $parentname=getParentName($parent_id); - } - - $result[$col_arr[$k]]=$parentname; - } - if($ui_type[$fld_arr[$k]] ==53 || $ui_type[$fld_arr[$k]] ==52) - { - if($result[$col_arr[$k]] != '') - { - $owner=getOwnerName($result[$col_arr[$k]]); - } - $result[$col_arr[$k]]=$owner; - } - if($ui_type[$fld_arr[$k]] ==50 or $ui_type[$fld_arr[$k]] ==51) - { - if($module!='Products') { - $entity_name=getAccountName($result[$col_arr[$k]]); - } else { - $entity_name=getProductName($result[$col_arr[$k]]); - } - if($entity_name != '') { - $result[$col_arr[$k]]=$entity_name; - } else { - $result[$col_arr[$k]]=''; - } - } - if($ui_type[$fld_arr[$k]] ==58) - { - $campaign_name=getCampaignName($result[$col_arr[$k]]); - if($campaign_name != '') - $result[$col_arr[$k]]=$campaign_name; - else $result[$col_arr[$k]]=''; - } - if($ui_type[$fld_arr[$k]] == 59) - { - $product_name=getProductName($result[$col_arr[$k]]); - if($product_name != '') - $result[$col_arr[$k]]=$product_name; - else $result[$col_arr[$k]]=''; - } - /*uitype 10 handling*/ - if($ui_type[$fld_arr[$k]] == 10){ - $result[$col_arr[$k]] = getRecordInfoFromID($result[$col_arr[$k]]); - } - if($ui_type[$fld_arr[$k]] == 5 || $ui_type[$fld_arr[$k]] == 6 || $ui_type[$fld_arr[$k]] == 23){ - if ($$result[$col_arr[$k]] != '' && $$result[$col_arr[$k]] != '0000-00-00') { - $date = new DateTimeField($$result[$col_arr[$k]]); - $value = $date->getDisplayDate(); - if(strpos($$result[$col_arr[$k]], ' ') > -1) { - $value .= (' ' . $date->getDisplayTime()); - } - } elseif ($$result[$col_arr[$k]] == '0000-00-00') { - $value = ''; - } else { - $value = $$result[$col_arr[$k]]; - } - $result[$col_arr[$k]] = $value; - } - if($ui_type[$fld_arr[$k]] == 71) { - $result[$col_arr[$k]] = CurrencyField::convertToUserFormat($result[$col_arr[$k]]); - } - if($ui_type[$fld_arr[$k]] == 72) { - $result[$col_arr[$k]] = CurrencyField::convertToUserFormat($result[$col_arr[$k]], null, true); - } - - $fld_values[$grp][$ii][$fld_labl_arr[$k]] = $result[$col_arr[$k]]; - - } - $fld_values[$grp][$ii]['Entity Type'] = $result['deleted']; - $ii++; - $rec_cnt++; - } - - $gro="group"; - for($i=0;$i<$no_rows;$i++) - { - $ii=0; - $dis_group[]=$fld_values[$gro.$i][$ii]; - $count_group[$i]=count($fld_values[$gro.$i]); - $ii++; - $new_group[]=$dis_group[$i]; - } - $fld_nam=$new_group[0]; - $ret_arr[0]=$fld_values; - $ret_arr[1]=$fld_nam; - $ret_arr[2]=$ui_type; - $ret_arr["navigation"]=$navigationOutput; - return $ret_arr; -} - -/** Function to get on clause criteria for sub tables like address tables to construct duplicate check query */ -function get_special_on_clause($field_list) -{ - $field_array = explode(",",$field_list); - $ret_str = ''; - $sel_clause = ''; - $i=1; - $cnt = count($field_array); - $spl_chk = ($_REQUEST['modulename'] != '')?$_REQUEST['modulename']:$_REQUEST['module']; - foreach($field_array as $fld) - { - $sub_arr = explode(".",$fld); - $tbl_name = $sub_arr[0]; - $col_name = $sub_arr[1]; - $fld_name = $sub_arr[2]; - - //need to handle aditional conditions with sub tables for further modules of duplicate check - if($tbl_name == 'vtiger_leadsubdetails' || $tbl_name == 'vtiger_contactsubdetails') - $tbl_alias = "subd"; - else if($tbl_name == 'vtiger_leadaddress' || $tbl_name == 'vtiger_contactaddress') - $tbl_alias = "addr"; - else if($tbl_name == 'vtiger_account' && $spl_chk == 'Contacts') - $tbl_alias = "acc"; - else if($tbl_name == 'vtiger_accountbillads') - $tbl_alias = "badd"; - else if($tbl_name == 'vtiger_accountshipads') - $tbl_alias = "sadd"; - else if($tbl_name == 'vtiger_crmentity') - $tbl_alias = "crm"; - else if($tbl_name == 'vtiger_customerdetails') - $tbl_alias = "custd"; - else if($tbl_name == 'vtiger_contactdetails' && spl_chk == 'HelpDesk') - $tbl_alias = "contd"; - else if(stripos($tbl_name, 'cf') === (strlen($tbl_name) - strlen('cf'))) - $tbl_alias = "tcf"; // Custom Field Table Prefix to use in subqueries - else - $tbl_alias = "t"; - - $sel_clause .= $tbl_alias.".".$col_name.","; - $ret_str .= " $tbl_name.$col_name = $tbl_alias.$col_name"; - if ($cnt != $i) $ret_str .= " and "; - $i++; - } - $ret_arr['on_clause'] = $ret_str; - $ret_arr['sel_clause'] = trim($sel_clause,","); - return $ret_arr; -} - -/** Function to get on clause criteria for duplicate check queries */ -function get_on_clause($field_list,$uitype_arr,$module) -{ - $field_array = explode(",",$field_list); - $ret_str = ''; - $i=1; - foreach($field_array as $fld) - { - $sub_arr = explode(".",$fld); - $tbl_name = $sub_arr[0]; - $col_name = $sub_arr[1]; - $fld_name = $sub_arr[2]; - - $ret_str .= " ifnull($tbl_name.$col_name,'null') = ifnull(temp.$col_name,'null')"; - - if (count($field_array) != $i) $ret_str .= " and "; - $i++; - } - return $ret_str; -} - -/** call back function to change the array values in to lower case */ -function lower_array(&$string){ - $string = strtolower(trim($string)); -} - -/** Function to get recordids for subquery where condition */ -// TODO - Need to check if this method is used anywhere? -function get_subquery_recordids($sub_query) -{ - global $adb; - //need to update this module whenever duplicate check tool added for new modules - $module_id_array = Array("Accounts"=>"accountid","Contacts"=>"contactid","Leads"=>"leadid","Products"=>"productid","HelpDesk"=>"ticketid","Potentials"=>"potentialid","Vendors"=>"vendorid"); - $id = ($module_id_array[$_REQUEST['modulename']] != '')?$module_id_array[$_REQUEST['modulename']]:$module_id_array[$_REQUEST['module']]; - $sub_res = ''; - $sub_result = $adb->query($sub_query); - $row_count = $adb->num_rows($sub_result); - $sub_res = ''; - if($row_count > 0) - { - while($rows = $adb->fetchByAssoc($sub_result)) - { - $sub_res .= $rows[$id].","; - } - $sub_res = trim($sub_res,","); - } - else - $sub_res .= "''"; - return $sub_res; -} - -/** Function to get tablename, columnname, fieldname, fieldlabel and uitypes of fields of merge criteria for a particular module*/ -function getFieldValues($module) -{ - global $adb,$current_user; - - //In future if we want to change a id mapping to name or other string then we can add that elements in this array. - //$fld_table_arr = Array("vtiger_contactdetails.account_id"=>"vtiger_account.accountname"); - //$special_fld_arr = Array("account_id"=>"accountname"); - - $fld_table_arr = Array(); - $special_fld_arr = Array(); - $tabid = getTabid($module); - - $fieldname_query="select fieldname,fieldlabel,uitype,tablename,columnname from vtiger_field where fieldid in - (select fieldid from vtiger_user2mergefields WHERE tabid=? AND userid=? AND visible = ?) and vtiger_field.presence in (0,2)"; - $fieldname_result = $adb->pquery($fieldname_query, array($tabid, $current_user->id, 1)); - - $field_num_rows = $adb->num_rows($fieldname_result); - - $fld_arr = array(); - $col_arr = array(); - for($j=0;$j< $field_num_rows;$j ++) - { - $tablename = $adb->query_result($fieldname_result,$j,'tablename'); - $column_name = $adb->query_result($fieldname_result,$j,'columnname'); - $field_name = $adb->query_result($fieldname_result,$j,'fieldname'); - $field_lbl = $adb->query_result($fieldname_result,$j,'fieldlabel'); - $ui_type = $adb->query_result($fieldname_result,$j,'uitype'); - $table_col = $tablename.".".$column_name; - if(getFieldVisibilityPermission($module,$current_user->id,$field_name) == 0) - { - $fld_name = ($special_fld_arr[$field_name] != '')?$special_fld_arr[$field_name]:$field_name; - - $fld_arr[] = $fld_name; - $col_arr[] = $column_name; - if($fld_table_arr[$table_col] != '') - $table_col = $fld_table_arr[$table_col]; - - $field_values_array['fieldnames_list'][] = $table_col . "." . $fld_name; - $fld_labl_arr[]=$field_lbl; - $uitype[$field_name]=$ui_type; - } - } - $field_values_array['fieldnames_list']=implode(",",$field_values_array['fieldnames_list']); - $field_values=implode(",",$fld_arr); - $field_values_array['fieldnames']=$field_values; - $field_values_array["fieldnames_array"]=$fld_arr; - $field_values_array["columnnames_array"]=$col_arr; - $field_values_array['fieldlabels_array']=$fld_labl_arr; - $field_values_array['fieldname_uitype']=$uitype; - - return $field_values_array; -} - -/** To get security parameter for a particular module -- By Pavani*/ -function getSecParameterforMerge($module) -{ - global $current_user; - $tab_id = getTabid($module); - $sec_parameter=""; - require('user_privileges/user_privileges_'.$current_user->id.'.php'); - require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); - if($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) - { - if($module == "Vendors") { - $sec_parameter = ""; - } else { - $sec_parameter=getListViewSecurityParameter($module); - if($module == "Accounts") { - $sec_parameter .= " AND (vtiger_crmentity.smownerid IN (".$current_user->id.") - OR vtiger_crmentity.smownerid IN ( - SELECT vtiger_user2role.userid - FROM vtiger_user2role - INNER JOIN vtiger_users - ON vtiger_users.id = vtiger_user2role.userid - INNER JOIN vtiger_role - ON vtiger_role.roleid = vtiger_user2role.roleid - WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%') - OR vtiger_crmentity.smownerid IN ( - SELECT shareduserid - FROM vtiger_tmp_read_user_sharing_per - WHERE userid=".$current_user->id." - AND tabid=".$tab_id.") - OR (vtiger_crmentity.smownerid in (0) - AND ("; - - if(sizeof($current_user_groups) > 0) { - $sec_parameter .= " vtiger_groups.groupname IN ( - SELECT groupname - FROM vtiger_groups - WHERE groupid IN (". implode(",", getCurrentUserGroupList()) .")) - OR "; - } - $sec_parameter .= " vtiger_groups.groupname IN ( - SELECT vtiger_groups.groupname - FROM vtiger_tmp_read_group_sharing_per - INNER JOIN vtiger_groups - ON vtiger_groups.groupid = vtiger_tmp_read_group_sharing_per.sharedgroupid - WHERE userid=".$current_user->id." - AND tabid=".$tab_id.")))) "; - } - } - } - return $sec_parameter; -} - -// Update all the data refering to currency $old_cur to $new_cur -function transferCurrency($old_cur, $new_cur) { - - // Transfer User currency to new currency - transferUserCurrency($old_cur, $new_cur); - - // Transfer Product Currency to new currency - transferProductCurrency($old_cur, $new_cur); - - // Transfer PriceBook Currency to new currency - transferPriceBookCurrency($old_cur, $new_cur); -} - -// Function to transfer the users with currency $old_cur to $new_cur as currency -function transferUserCurrency($old_cur, $new_cur) { - global $log, $adb, $current_user; - $log->debug("Entering function transferUserCurrency..."); - - $sql = "update vtiger_users set currency_id=? where currency_id=?"; - $adb->pquery($sql, array($new_cur, $old_cur)); - - $current_user->retrieve_entity_info($current_user->id,"Users"); - $log->debug("Exiting function transferUserCurrency..."); -} - -// Function to transfer the products with currency $old_cur to $new_cur as currency -function transferProductCurrency($old_cur, $new_cur) { - global $log, $adb; - $log->debug("Entering function updateProductCurrency..."); - $prod_res = $adb->pquery("select productid from vtiger_products where currency_id = ?", array($old_cur)); - $numRows = $adb->num_rows($prod_res); - $prod_ids = array(); - for($i=0;$i<$numRows;$i++) { - $prod_ids[] = $adb->query_result($prod_res,$i,'productid'); - } - if(count($prod_ids) > 0) { - $prod_price_list = getPricesForProducts($new_cur,$prod_ids); - - for($i=0;$ipquery($query, $params); - } - } - $log->debug("Exiting function updateProductCurrency..."); -} - -// Function to transfer the pricebooks with currency $old_cur to $new_cur as currency -// and to update the associated products with list price in $new_cur currency -function transferPriceBookCurrency($old_cur, $new_cur) { - global $log, $adb; - $log->debug("Entering function updatePriceBookCurrency..."); - $pb_res = $adb->pquery("select pricebookid from vtiger_pricebook where currency_id = ?", array($old_cur)); - $numRows = $adb->num_rows($pb_res); - $pb_ids = array(); - for($i=0;$i<$numRows;$i++) { - $pb_ids[] = $adb->query_result($pb_res,$i,'pricebookid'); - } - - if(count($pb_ids) > 0) { - require_once('modules/PriceBooks/PriceBooks.php'); - - for($i=0;$iid = $pb_id; - $focus->mode = 'edit'; - $focus->retrieve_entity_info($pb_id, "PriceBooks"); - $focus->column_fields['currency_id'] = $new_cur; - $focus->save("PriceBooks"); - } - } - - $log->debug("Exiting function updatePriceBookCurrency..."); -} - -//functions for asterisk integration start -/** - * this function returns the caller name based on the phone number that is passed to it - * @param $from - the number which is calling - * returns caller information in name(type) format :: for e.g. Mary Smith (Contact) - * if no information is present in database, it returns :: Unknown Caller (Unknown) - */ -function getCallerName($from) { - global $adb; - - //information found - $callerInfo = getCallerInfo($from); - - if($callerInfo != false){ - $callerName = decode_html($callerInfo['name']); - $module = $callerInfo['module']; - $callerModule = " ($module)"; - $callerID = $callerInfo['id']; - - $caller =$caller."$callerName$callerModule"; - - }else{ - $caller = $caller."
- ".getTranslatedString('LBL_CREATE_LEAD')."
- ".getTranslatedString('LBL_CREATE_CONTACT')."
- ".getTranslatedString('LBL_CREATE_ACCOUNT').""; - } - return $caller; -} - -/** - * this function searches for a given number in vtiger and returns the callerInfo in an array format - * currently the search is made across only leads, accounts and contacts modules - * - * @param $number - the number whose information you want - * @return array in format array(name=>callername, module=>module, id=>id); - */ -function getCallerInfo($number){ - global $adb, $log; - if(empty($number)){ - return false; - } - $caller = "Unknown Number (Unknown)"; //declare caller as unknown in beginning - - $params = array(); - $name = array('Contacts', 'Accounts', 'Leads'); - foreach ($name as $module) { - $focus = CRMEntity::getInstance($module); - $query = $focus->buildSearchQueryForFieldTypes(11, $number); - if(empty($query)) return; - - $result = $adb->pquery($query, array()); - if($adb->num_rows($result) > 0 ){ - $callerName = $adb->query_result($result, 0, "name"); - $callerID = $adb->query_result($result,0,'id'); - $data = array("name"=>$callerName, "module"=>$module, "id"=>$callerID); - return $data; - } - } - return false; -} - -/** - * this function returns the tablename and primarykeys for a given module in array format - * @param object $adb - peardatabase type object - * @param string $module - module name for which you want the array - * @return array(tablename1=>primarykey1,.....) - */ -function get_tab_name_index($adb, $module){ - $tabid = getTabid($module); - $sql = "select * from vtiger_tab_name_index where tabid = ?"; - $result = $adb->pquery($sql, array($tabid)); - $count = $adb->num_rows($result); - $data = array(); - - for($i=0; $i<$count; $i++){ - $tablename = $adb->query_result($result, $i, "tablename"); - $primaryKey = $adb->query_result($result, $i, "primarykey"); - $data[$tablename] = $primaryKey; - } - return $data; -} - -/** - * this function returns the value of use_asterisk from the database for the current user - * @param string $id - the id of the current user - */ -function get_use_asterisk($id){ - global $adb; - if(!vtlib_isModuleActive('PBXManager') || isPermitted('PBXManager', 'index') == 'no'){ - return false; - } - $sql = "select * from vtiger_asteriskextensions where userid = ?"; - $result = $adb->pquery($sql, array($id)); - if($adb->num_rows($result)>0){ - $use_asterisk = $adb->query_result($result, 0, "use_asterisk"); - $asterisk_extension = $adb->query_result($result, 0, "asterisk_extension"); - if($use_asterisk == 0 || empty($asterisk_extension)){ - return 'false'; - }else{ - return 'true'; - } - }else{ - return 'false'; - } -} - -/** - * this function adds a record to the callhistory module - * - * @param string $userExtension - the extension of the current user - * @param string $callfrom - the caller number - * @param string $callto - the called number - * @param string $status - the status of the call (outgoing/incoming/missed) - * @param object $adb - the peardatabase object - */ -function addToCallHistory($userExtension, $callfrom, $callto, $status, $adb, $useCallerInfo){ - $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?"; - $result = $adb->pquery($sql,array($userExtension)); - $userID = $adb->query_result($result, 0, "userid"); - if(empty($userID)) { - // we have observed call to extension not configured in Vtiger will returns NULL - return; - } - $crmID = $adb->getUniqueID('vtiger_crmentity'); - $timeOfCall = date('Y-m-d H:i:s'); - - $sql = "insert into vtiger_crmentity values (?,?,?,?,?,?,?,?,?,?,?,?,?)"; - $params = array($crmID, $userID, $userID, 0, "PBXManager", "", $timeOfCall, $timeOfCall, NULL, NULL, 0, 1, 0); - $adb->pquery($sql, $params); - - if(empty($callfrom)){ - $callfrom = "Unknown"; - } - if(empty($callto)){ - $callto = "Unknown"; - } - - if($status == 'outgoing'){ - //call is from user to record - $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?"; - $result = $adb->pquery($sql, array($callfrom)); - if($adb->num_rows($result)>0){ - $userid = $adb->query_result($result, 0, "userid"); - $callerName = getUserFullName($userid); - } - - $receiver = $useCallerInfo; - if(empty($receiver)){ - $receiver = "Unknown"; - }else{ - $receiver = "".$receiver['name'].""; - } - }else{ - //call is from record to user - $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?"; - $result = $adb->pquery($sql,array($callto)); - if($adb->num_rows($result)>0){ - $userid = $adb->query_result($result, 0, "userid"); - $receiver = getUserFullName($userid); - } - $callerName = $useCallerInfo; - if(empty($callerName)){ - $callerName = "Unknown $callfrom"; - }else{ - $callerName = "".decode_html($callerName['name']).""; - } - } - - $sql = "insert into vtiger_pbxmanager (pbxmanagerid,callfrom,callto,timeofcall,status)values (?,?,?,?,?)"; - $params = array($crmID, $callerName, $receiver, $timeOfCall, $status); - $adb->pquery($sql, $params); - return $crmID; -} -//functions for asterisk integration end - -//functions for settings page -/** - * this function returns the blocks for the settings page - */ -function getSettingsBlocks(){ - global $adb; - $sql = "select * from vtiger_settings_blocks order by sequence"; - $result = $adb->query($sql); - $count = $adb->num_rows($result); - $blocks = array(); - - if($count>0){ - for($i=0;$i<$count;$i++){ - $blockid = $adb->query_result($result, $i, "blockid"); - $label = $adb->query_result($result, $i, "label"); - $blocks[$blockid] = $label; - } - } - return $blocks; -} - -/** - * this function returns the fields for the settings page - */ -function getSettingsFields(){ - global $adb; - $sql = "select * from vtiger_settings_field where blockid!=? and active=0 order by blockid,sequence"; - $result = $adb->pquery($sql, array(getSettingsBlockId('LBL_MODULE_MANAGER'))); - $count = $adb->num_rows($result); - $fields = array(); - - if($count>0){ - for($i=0;$i<$count;$i++){ - $blockid = $adb->query_result($result, $i, "blockid"); - $iconpath = $adb->query_result($result, $i, "iconpath"); - $description = $adb->query_result($result, $i, "description"); - $linkto = $adb->query_result($result, $i, "linkto"); - $action = getPropertiesFromURL($linkto, "action"); - $module = getPropertiesFromURL($linkto, "module"); - $name = $adb->query_result($result, $i, "name"); - - $fields[$blockid][] = array("icon"=>$iconpath, "description"=>$description, "link"=>$linkto, "name"=>$name, "action"=>$action, "module"=>$module); - } - - //add blanks for 4-column layout - foreach($fields as $blockid=>&$field){ - if(count($field)>0 && count($field)<4){ - for($i=count($field);$i<4;$i++){ - $field[$i] = array(); - } - } - } - } - return $fields; -} - -/** - * this function takes an url and returns the module name from it - */ -function getPropertiesFromURL($url, $action){ - $result = array(); - preg_match("/$action=([^&]+)/",$url,$result); - return $result[1]; -} - -//functions for settings page end - -/* Function to get the name of the Field which is used for Module Specific Sequence Numbering, if any - * @param module String - Module label - * return Array - Field name and label are returned */ -function getModuleSequenceField($module) { - global $adb, $log; - $log->debug("Entering function getModuleSequenceFieldName ($module)..."); - $field = null; - - if (!empty($module)) { - - // First look at the cached information - $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); - - if($cachedModuleFields === false) { - //uitype 4 points to Module Numbering Field - $seqColRes = $adb->pquery("SELECT fieldname, fieldlabel, columnname FROM vtiger_field WHERE uitype=? AND tabid=? and vtiger_field.presence in (0,2)", array('4', getTabid($module))); - if($adb->num_rows($seqColRes) > 0) { - $fieldname = $adb->query_result($seqColRes,0,'fieldname'); - $columnname = $adb->query_result($seqColRes,0,'columnname'); - $fieldlabel = $adb->query_result($seqColRes,0,'fieldlabel'); - - $field = array(); - $field['name'] = $fieldname; - $field['column'] = $columnname; - $field['label'] = $fieldlabel; - } - } else { - - foreach($cachedModuleFields as $fieldinfo) { - if($fieldinfo['uitype'] == '4') { - $field = array(); - - $field['name'] = $fieldinfo['fieldname']; - $field['column'] = $fieldinfo['columnname']; - $field['label'] = $fieldinfo['fieldlabel']; - - break; - } - } - } - } - - $log->debug("Exiting getModuleSequenceFieldName..."); - return $field; -} - -/* Function to get the Result of all the field ids allowed for Duplicates merging for specified tab/module (tabid) */ -function getFieldsResultForMerge($tabid) { - global $log, $adb; - $log->debug("Entering getFieldsResultForMerge(".$tabid.") method ..."); - - $nonmergable_tabids = array(29); - - if (in_array($tabid, $nonmergable_tabids)) { - return null; - } - - // List of Fields not allowed for Duplicates Merging based on the module (tabid) [tabid to fields mapping] - $nonmergable_field_tab = Array( - 4 => array('portal','imagename'), - 13 => array('update_log','filename','comments'), - ); - - $nonmergable_displaytypes = Array(4); - $nonmergable_uitypes = Array('70','69','4'); - - $sql = "SELECT fieldid,typeofdata FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2) AND block IS NOT NULL"; - $params = array($tabid); - - $where = ''; - - if (isset($nonmergable_field_tab[$tabid]) && count($nonmergable_field_tab[$tabid]) > 0) { - $where .= " AND fieldname NOT IN (". generateQuestionMarks($nonmergable_field_tab[$tabid]) .")"; - array_push($params, $nonmergable_field_tab[$tabid]); - } - - if (count($nonmergable_displaytypes) > 0) { - $where .= " AND displaytype NOT IN (". generateQuestionMarks($nonmergable_displaytypes) .")"; - array_push($params, $nonmergable_displaytypes); - } - if (count($nonmergable_uitypes) > 0) { - $where .= " AND uitype NOT IN ( ". generateQuestionMarks($nonmergable_uitypes) .")" ; - array_push($params, $nonmergable_uitypes); - } - - if (trim($where) != '') { - $sql .= $where; - } - - $res = $adb->pquery($sql, $params); - $log->debug("Exiting getFieldsResultForMerge method ..."); - return $res; -} - -/* Function to get the related tables data - * @param - $module - Primary module name - * @param - $secmodule - Secondary module name - * return Array $rel_array tables and fields to be compared are sent - * */ -function getRelationTables($module,$secmodule){ - global $adb; - $primary_obj = CRMEntity::getInstance($module); - $secondary_obj = CRMEntity::getInstance($secmodule); - - $ui10_query = $adb->pquery("SELECT vtiger_field.tabid AS tabid,vtiger_field.tablename AS tablename, vtiger_field.columnname AS columnname FROM vtiger_field INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid WHERE (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?) OR (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?)",array($module,$secmodule,$secmodule,$module)); - if($adb->num_rows($ui10_query)>0){ - $ui10_tablename = $adb->query_result($ui10_query,0,'tablename'); - $ui10_columnname = $adb->query_result($ui10_query,0,'columnname'); - $ui10_tabid = $adb->query_result($ui10_query,0,'tabid'); - - if($primary_obj->table_name == $ui10_tablename){ - $reltables = array($ui10_tablename=>array("".$primary_obj->table_index."","$ui10_columnname")); - } else if($secondary_obj->table_name == $ui10_tablename){ - $reltables = array($ui10_tablename=>array("$ui10_columnname","".$secondary_obj->table_index.""),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); - } else { - if(isset($secondary_obj->tab_name_index[$ui10_tablename])){ - $rel_field = $secondary_obj->tab_name_index[$ui10_tablename]; - $reltables = array($ui10_tablename=>array("$ui10_columnname","$rel_field"),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); - } else { - $rel_field = $primary_obj->tab_name_index[$ui10_tablename]; - $reltables = array($ui10_tablename=>array("$rel_field","$ui10_columnname"),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); - } - } - }else { - if(method_exists($primary_obj,setRelationTables)){ - $reltables = $primary_obj->setRelationTables($secmodule); - } else { - $reltables = ''; - } - } - if(is_array($reltables) && !empty($reltables)){ - $rel_array = $reltables; - } else { - $rel_array = array("vtiger_crmentityrel"=>array("crmid","relcrmid"),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); - } - return $rel_array; -} - -/** - * This function returns no value but handles the delete functionality of each entity. - * Input Parameter are $module - module name, $return_module - return module name, $focus - module object, $record - entity id, $return_id - return entity id. - */ -function DeleteEntity($module,$return_module,$focus,$record,$return_id) { - global $log; - $log->debug("Entering DeleteEntity method ($module, $return_module, $record, $return_id)"); - - if ($module != $return_module && !empty($return_module) && !empty($return_id)) { - $focus->unlinkRelationship($record, $return_module, $return_id); - $focus->trackUnLinkedInfo($return_module, $return_id, $module, $record); - } else { - $focus->trash($module, $record); - } - $log->debug("Exiting DeleteEntity method ..."); -} - -/** - * Function to related two records of different entity types - */ -function relateEntities($focus, $sourceModule, $sourceRecordId, $destinationModule, $destinationRecordIds) { - if(!is_array($destinationRecordIds)) $destinationRecordIds = Array($destinationRecordIds); - foreach($destinationRecordIds as $destinationRecordId) { - $focus->save_related_module($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId); - $focus->trackLinkedInfo($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId); - } - -} - -/* Function to install Vtlib Compliant modules - * @param - $packagename - Name of the module - * @param - $packagepath - Complete path to the zip file of the Module - */ -function installVtlibModule($packagename, $packagepath, $customized=false) { - global $log; - require_once('vtlib/Vtiger/Package.php'); - require_once('vtlib/Vtiger/Module.php'); - $Vtiger_Utils_Log = true; - $package = new Vtiger_Package(); - - if($package->isLanguageType($packagepath)) { - $package = new Vtiger_Language(); - $package->import($packagepath, true); - return; - } - $module = $package->getModuleNameFromZip($packagepath); - - // Customization - if($package->isLanguageType()) { - require_once('vtlib/Vtiger/Language.php'); - $languagePack = new Vtiger_Language(); - @$languagePack->import($packagepath, true); - return; - } - // END - - $module_exists = false; - $module_dir_exists = false; - if($module == null) { - $log->fatal("$packagename Module zipfile is not valid!"); - } else if(Vtiger_Module::getInstance($module)) { - $log->fatal("$module already exists!"); - $module_exists = true; - } - if($module_exists == false) { - $log->debug("$module - Installation starts here"); - $package->import($packagepath, true); - $moduleInstance = Vtiger_Module::getInstance($module); - if (empty($moduleInstance)) { - $log->fatal("$module module installation failed!"); - } - } -} - -/* Function to update Vtlib Compliant modules - * @param - $module - Name of the module - * @param - $packagepath - Complete path to the zip file of the Module - */ -function updateVtlibModule($module, $packagepath) { - global $log; - require_once('vtlib/Vtiger/Package.php'); - require_once('vtlib/Vtiger/Module.php'); - $Vtiger_Utils_Log = true; - $package = new Vtiger_Package(); - - if($package->isLanguageType($packagepath)) { - require_once('vtlib/Vtiger/Language.php'); - $languagePack = new Vtiger_Language(); - $languagePack->update(null, $packagepath, true); - return; - } - - if($module == null) { - $log->fatal("Module name is invalid"); - } else { - $moduleInstance = Vtiger_Module::getInstance($module); - if($moduleInstance || $package->isModuleBundle($packagepath)) { - $log->debug("$module - Module instance found - Update starts here"); - $package->update($moduleInstance, $packagepath); - } else { - $log->fatal("$module doesn't exists!"); - } - } -} - -/* Function to only initialize the update of Vtlib Compliant modules - * @param - $module - Name of the module - * @param - $packagepath - Complete path to the zip file of the Module - */ -function initUpdateVtlibModule($module, $packagepath) { - global $log; - require_once('vtlib/Vtiger/Package.php'); - require_once('vtlib/Vtiger/Module.php'); - $Vtiger_Utils_Log = true; - $package = new Vtiger_Package(); - - if($module == null) { - $log->fatal("Module name is invalid"); - } else { - $moduleInstance = Vtiger_Module::getInstance($module); - if($moduleInstance) { - $log->debug("$module - Module instance found - Init Update starts here"); - $package->initUpdate($moduleInstance, $packagepath, true); - } else { - $log->fatal("$module doesn't exists!"); - } - } -} - -/** - * this function checks if a given column exists in a given table or not - * @param string $columnName - the columnname - * @param string $tableName - the tablename - * @return boolean $status - true if column exists; false otherwise - */ -function columnExists($columnName, $tableName){ - global $adb; - $columnNames = array(); - $columnNames = $adb->getColumnNames($tableName); - - if(in_array($columnName, $columnNames)){ - return true; - }else{ - return false; - } -} - -/* To get modules list for which work flow and field formulas is permitted*/ -function com_vtGetModules($adb) { - $sql="select distinct vtiger_field.tabid, name - from vtiger_field - inner join vtiger_tab - on vtiger_field.tabid=vtiger_tab.tabid - where vtiger_field.tabid not in(9,10,16,15,8,29) and vtiger_tab.presence = 0 and vtiger_tab.isentitytype=1"; - $it = new SqlResultIterator($adb, $adb->query($sql)); - $modules = array(); - foreach($it as $row) { - if(isPermitted($row->name,'index') == "yes") { - $modules[$row->name] = getTranslatedString($row->name); - } - } - return $modules; -} - -/** - * this function accepts a potential id returns the module name and entity value for the related field - * @param integer $id - the potential id - * @return array $data - the related module name and field value - */ -function getRelatedInfo($id){ - global $adb; - $data = array(); - $sql = "select related_to from vtiger_potential where potentialid=?"; - $result = $adb->pquery($sql, array($id)); - if($adb->num_rows($result)>0){ - $relID = $adb->query_result($result, 0, "related_to"); - $sql = "select setype from vtiger_crmentity where crmid=?"; - $result = $adb->pquery($sql, array($relID)); - if($adb->num_rows($result)>0){ - $setype = $adb->query_result($result, 0, "setype"); - } - $data = array("setype"=>$setype, "relID"=>$relID); - } - return $data; -} - -/** - * this function accepts an ID and returns the entity value for that id - * @param integer $id - the crmid of the record - * @return string $data - the entity name for the id - */ -function getRecordInfoFromID($id){ - global $adb; - $data = array(); - $sql = "select setype from vtiger_crmentity where crmid=?"; - $result = $adb->pquery($sql, array($id)); - if($adb->num_rows($result)>0){ - $setype = $adb->query_result($result, 0, "setype"); - $data = getEntityName($setype, $id); - } - $data = array_values($data); - $data = $data[0]; - return $data; -} - -/** - * this function accepts an tabiD and returns the tablename, fieldname and fieldlabel for email field - * @param integer $tabid - the tabid of current module - * @return string $fields - the array of mail field's tablename, fieldname and fieldlabel - */ -function getMailFields($tabid){ - global $adb; - $fields = array(); - $result = $adb->pquery("SELECT tablename,fieldlabel,fieldname FROM vtiger_field WHERE tabid=? AND uitype IN (13,104)", array($tabid)); - if($adb->num_rows($result)>0){ - $tablename = $adb->query_result($result, 0, "tablename"); - $fieldname = $adb->query_result($result, 0, "fieldname"); - $fieldlabel = $adb->query_result($result, 0, "fieldlabel"); - $fields = array("tablename"=>$tablename,"fieldname"=>$fieldname,"fieldlabel"=>$fieldlabel); - } - return $fields; -} - -/** - * Function to check if a given record exists (not deleted) - * @param integer $recordId - record id - */ -function isRecordExists($recordId) { - global $adb; - $query = "SELECT crmid FROM vtiger_crmentity where crmid=? AND deleted=0"; - $result = $adb->pquery($query, array($recordId)); - if ($adb->num_rows($result)) { - return true; - } - return false; -} - -/** Function to set date values compatible to database (YY_MM_DD) - * @param $value -- value :: Type string - * @returns $insert_date -- insert_date :: Type string - */ -function getValidDBInsertDateValue($value) { - global $log; - $log->debug("Entering getValidDBInsertDateValue(".$value.") method ..."); - $value = trim($value); - $delim = array('/','.'); - foreach ($delim as $delimiter){ - $x = strpos($value, $delimiter); - if($x === false) continue; - else{ - $value=str_replace($delimiter, '-', $value); - break; - } - } - list($y,$m,$d) = explode('-',$value); - if(strlen($y) == 1) $y = '0'.$y; - if(strlen($m) == 1) $m = '0'.$m; - if(strlen($d) == 1) $d = '0'.$d; - $value = implode('-', array($y,$m,$d)); - - if(strlen($y)<4){ - $insert_date = DateTimeField::convertToDBFormat($value); - } else { - $insert_date = $value; - } - - if (preg_match("/^[0-9]{2,4}[-][0-1]{1,2}?[0-9]{1,2}[-][0-3]{1,2}?[0-9]{1,2}$/", $insert_date) == 0) { - return ''; - } - - $log->debug("Exiting getValidDBInsertDateValue method ..."); - return $insert_date; -} - -function getValidDBInsertDateTimeValue($value) { - $value = trim($value); - $valueList = explode(' ',$value); - if(count($valueList) == 2) { - $dbDateValue = getValidDBInsertDateValue($valueList[0]); - $dbTimeValue = $valueList[1]; - if(!empty($dbTimeValue) && strpos($dbTimeValue, ':') === false) { - $dbTimeValue = $dbTimeValue.':'; - } - $timeValueLength = strlen($dbTimeValue); - if(!empty($dbTimeValue) && strrpos($dbTimeValue, ':') == ($timeValueLength-1)) { - $dbTimeValue = $dbTimeValue.'00'; - } - try { - $dateTime = new DateTimeField($dbDateValue.' '.$dbTimeValue); - return $dateTime->getDBInsertDateTimeValue(); - } catch (Exception $ex) { - return ''; - } - } elseif(count($valueList == 1)) { - return getValidDBInsertDateValue($value); - } -} - -/** Function to set the PHP memory limit to the specified value, if the memory limit set in the php.ini is less than the specified value - * @param $newvalue -- Required Memory Limit - */ -function _phpset_memorylimit_MB($newvalue) { - $current = @ini_get('memory_limit'); - if(preg_match("/(.*)M/", $current, $matches)) { - // Check if current value is less then new value - if($matches[1] < $newvalue) { - @ini_set('memory_limit', "{$newvalue}M"); - } - } -} - -/** Function to sanitize the upload file name when the file name is detected to have bad extensions - * @param String -- $fileName - File name to be sanitized - * @return String - Sanitized file name - */ -function sanitizeUploadFileName($fileName, $badFileExtensions) { - - $fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename - $fileName = rtrim($fileName, '\\/<>?*:"<>|'); - - $fileNameParts = explode(".", $fileName); - $countOfFileNameParts = count($fileNameParts); - $badExtensionFound = false; - - for ($i=0;$i<$countOfFileNameParts;++$i) { - $partOfFileName = $fileNameParts[$i]; - if(in_array(strtolower($partOfFileName), $badFileExtensions)) { - $badExtensionFound = true; - $fileNameParts[$i] = $partOfFileName . 'file'; - } - } - - $newFileName = implode(".", $fileNameParts); - - if ($badExtensionFound) { - $newFileName .= ".txt"; - } - return $newFileName; -} - -/** Function to get the tab meta information for a given id - * @param $tabId -- tab id :: Type integer - * @returns $tabInfo -- array of preference name to preference value :: Type array - */ -function getTabInfo($tabId) { - global $adb; - - $tabInfoResult = $adb->pquery('SELECT prefname, prefvalue FROM vtiger_tab_info WHERE tabid=?', array($tabId)); - $tabInfo = array(); - for($i=0; $i<$adb->num_rows($tabInfoResult); ++$i) { - $prefName = $adb->query_result($tabInfoResult, $i, 'prefname'); - $prefValue = $adb->query_result($tabInfoResult, $i, 'prefvalue'); - $tabInfo[$prefName] = $prefValue; - } -} - -/** Function to return block name - * @param Integer -- $blockid - * @return String - Block Name - */ -function getBlockName($blockid) { - global $adb; - - $blockname = VTCacheUtils::lookupBlockLabelWithId($blockid); - - if(!empty($blockid) && $blockname === false){ - $block_res = $adb->pquery('SELECT blocklabel FROM vtiger_blocks WHERE blockid = ?',array($blockid)); - if($adb->num_rows($block_res)){ - $blockname = $adb->query_result($block_res,0,'blocklabel'); - } else { - $blockname = ''; - } - VTCacheUtils::updateBlockLabelWithId($blockname, $blockid); - } - return $blockname; -} - -function validateAlphaNumericInput($string){ - preg_match('/^[\w _\-]+$/', $string, $matches); - if(count($matches) == 0) { - return false; - } - return true; -} - -function validateServerName($string){ - preg_match('/^[\w\-\.\\/:]+$/', $string, $matches); - if(count($matches) == 0) { - return false; - } - return true; -} - -function validateEmailId($string){ - preg_match('/^[a-zA-Z0-9]+([\_\-\.]*[a-zA-Z0-9]+[\_\-]?)*@[a-zA-Z0-9]+([\_\-]?[a-zA-Z0-9]+)*\.+([\-\_]?[a-zA-Z0-9])+(\.?[a-zA-Z0-9]+)*$/', $string, $matches); - if(count($matches) == 0) { - return false; - } - return true; -} - -function str_rsplit($string, $splitLength) { - $reverseString = strrev($string); - $chunks = str_split($reverseString, $splitLength); - return array_reverse($chunks); -} - -/** - * Function to get the list of Contacts related to an activity - * @param Integer $activityId - * @return Array $contactsList - List of Contact ids, mapped to Contact Names - */ -function getActivityRelatedContacts($activityId) { - $adb = PearDatabase::getInstance(); - - $query = 'SELECT * FROM vtiger_cntactivityrel WHERE activityid=?'; - $result = $adb->pquery($query, array($activityId)); - - $noOfContacts = $adb->num_rows($result); - $contactsList = array(); - for ($i = 0; $i < $noOfContacts; ++$i) { - $contactId = $adb->query_result($result, $i, 'contactid'); - $displayValueArray = getEntityName('Contacts', $contactId); - if (!empty($displayValueArray)) { - foreach ($displayValueArray as $key => $field_value) { - $contact_name = $field_value; - } - } else { - $contact_name=''; - } - $contactsList[$contactId] = $contact_name; - } - return $contactsList; -} - -function isLeadConverted($leadId) { - $adb = PearDatabase::getInstance(); - - $query = 'SELECT converted FROM vtiger_leaddetails WHERE converted = 1 AND leadid=?'; - $params = array($leadId); - - $result = $adb->pquery($query, $params); - - if($result && $adb->num_rows($result) > 0) { - return true; - } - return false; -} - -function getSelectedRecords($input,$module,$idstring,$excludedRecords) { - global $current_user, $adb; - - if($idstring == 'relatedListSelectAll') { - - $recordid = vtlib_purify($input['recordid']); - if($module == 'Accounts') { - $result = getCampaignAccountIds($recordid); - } - if($module == 'Contacts') { - $result = getCampaignContactIds($recordid); - } - if($module == 'Leads') { - $result = getCampaignLeadIds($recordid); - } - $storearray = array(); - for ($i = 0; $i < $adb->num_rows($result); $i++) { - $storearray[] = $adb->query_result($result, $i, 'id'); - } - - $excludedRecords=explode(';',$excludedRecords); - $storearray=array_diff($storearray,$excludedRecords); - - } else if($module == 'Documents') { - - if($input['selectallmode']=='true') { - $result = getSelectAllQuery($input,$module); - $storearray = array(); - $focus = CRMEntity::getInstance($module); - - for ($i = 0; $i < $adb->num_rows($result); $i++) { - $storearray[] = $adb->query_result($result, $i, $focus->table_index); - } - - $excludedRecords = explode(';',$excludedRecords); - $storearray = array_diff($storearray,$excludedRecords); - if($idstring != 'all') { - $storearray = array_merge($storearray,explode(';',$idstring)); - } - $storearray = array_unique($storearray); - - } else { - $storearray = explode(";",$idstring); - } - - } elseif($idstring == 'all') { - - $result = getSelectAllQuery($input,$module); - $storearray = array(); - $focus = CRMEntity::getInstance($module); - - for ($i = 0; $i < $adb->num_rows($result); $i++) { - $storearray[] = $adb->query_result($result, $i, $focus->table_index); - } - - $excludedRecords = explode(';',$excludedRecords); - $storearray = array_diff($storearray,$excludedRecords); - - } else { - $storearray = explode(";",$idstring); - } - - return $storearray; -} - -function getSelectAllQuery($input,$module) { - global $adb,$current_user; - - $viewid = vtlib_purify($input['viewname']); - - if($module == "Calendar") { - $listquery = getListQuery($module); - $oCustomView = new CustomView($module); - $query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,$module); - $where = ''; - if($input['query'] == 'true') { - list($where, $ustring) = split("#@@#",getWhereCondition($module, $input)); - if(isset($where) && $where != '') { - $query .= " AND " .$where; - } - } - } else { - $queryGenerator = new QueryGenerator($module, $current_user); - $queryGenerator->initForCustomViewById($viewid); - - if($input['query'] == 'true') { - $queryGenerator->addUserSearchConditions($input); - } - - $queryGenerator->setFields(array('id')); - $query = $queryGenerator->getQuery(); - - if($module == 'Documents') { - $folderid = vtlib_purify($input['folderidstring']); - $folderid = str_replace(';', ',', $folderid); - $query .= " AND vtiger_notes.folderid in (".$folderid.")"; - } - } - - $result = $adb->pquery($query, array()); - return $result; -} - -function getCampaignAccountIds($id) { - global $adb; - $sql="SELECT vtiger_account.accountid as id FROM vtiger_account - INNER JOIN vtiger_campaignaccountrel ON vtiger_campaignaccountrel.accountid = vtiger_account.accountid - LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid - WHERE vtiger_campaignaccountrel.campaignid = ? AND vtiger_crmentity.deleted=0"; - $result = $adb->pquery($sql, array($id)); - return $result; -} - -function getCampaignContactIds($id) { - global $adb; - $sql="SELECT vtiger_contactdetails.contactid as id FROM vtiger_contactdetails - INNER JOIN vtiger_campaigncontrel ON vtiger_campaigncontrel.contactid = vtiger_contactdetails.contactid - LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid - WHERE vtiger_campaigncontrel.campaignid = ? AND vtiger_crmentity.deleted=0"; - $result = $adb->pquery($sql, array($id)); - return $result; -} - -function getCampaignLeadIds($id) { - global $adb; - $sql="SELECT vtiger_leaddetails.leadid as id FROM vtiger_leaddetails - INNER JOIN vtiger_campaignleadrel ON vtiger_campaignleadrel.leadid = vtiger_leaddetails.leadid - LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid - WHERE vtiger_campaignleadrel.campaignid = ? AND vtiger_crmentity.deleted=0"; - $result = $adb->pquery($sql, array($id)); - return $result; -} - -/** Function to get the difference between 2 datetime strings or millisecond values */ -function dateDiff($d1, $d2){ - $d1 = (is_string($d1) ? strtotime($d1) : $d1); - $d2 = (is_string($d2) ? strtotime($d2) : $d2); - - $diffSecs = abs($d1 - $d2); - $baseYear = min(date("Y", $d1), date("Y", $d2)); - $diff = mktime(0, 0, $diffSecs, 1, 1, $baseYear); - return array( - "years" => date("Y", $diff) - $baseYear, - "months_total" => (date("Y", $diff) - $baseYear) * 12 + date("n", $diff) - 1, - "months" => date("n", $diff) - 1, - "days_total" => floor($diffSecs / (3600 * 24)), - "days" => date("j", $diff) - 1, - "hours_total" => floor($diffSecs / 3600), - "hours" => date("G", $diff), - "minutes_total" => floor($diffSecs / 60), - "minutes" => (int) date("i", $diff), - "seconds_total" => $diffSecs, - "seconds" => (int) date("s", $diff) - ); -} - -/** -* Function to get the approximate difference between two date time values as string -*/ -function dateDiffAsString($d1, $d2) { - global $currentModule; - - $dateDiff = dateDiff($d1, $d2); - - $years = $dateDiff['years']; - $months = $dateDiff['months']; - $days = $dateDiff['days']; - $hours = $dateDiff['hours']; - $minutes = $dateDiff['minutes']; - $seconds = $dateDiff['seconds']; - - if($years > 0) { - $diffString = "$years ".getTranslatedString('LBL_YEARS',$currentModule); - } elseif($months > 0) { - $diffString = "$months ".getTranslatedString('LBL_MONTHS',$currentModule); - } elseif($days > 0) { - $diffString = "$days ".getTranslatedString('LBL_DAYS',$currentModule); - } elseif($hours > 0) { - $diffString = "$hours ".getTranslatedString('LBL_HOURS',$currentModule); - } elseif($minutes > 0) { - $diffString = "$minutes ".getTranslatedString('LBL_MINUTES',$currentModule); - } else { - $diffString = "$seconds ".getTranslatedString('LBL_SECONDS',$currentModule); - } - return $diffString; -} - -function getMinimumCronFrequency() { - if(file_exists('modules/Ondemand/Ondemand.config.php')) { - require_once('modules/Ondemand/Ondemand.config.php'); - global $VtigerOndemandConfig; - if($VtigerOndemandConfig['MINIMUM_CRON_FREQUENCY'] != '') - return $VtigerOndemandConfig['MINIMUM_CRON_FREQUENCY']; - } - global $MINIMUM_CRON_FREQUENCY; - - if(!empty($MINIMUM_CRON_FREQUENCY)) { - return $MINIMUM_CRON_FREQUENCY; - } - return 15; -} - +debug("Entering return_name(".$row.",".$first_column.",".$last_column.") method ..."); + $first_name = ""; + $last_name = ""; + $full_name = ""; + + if(isset($row[$first_column])) + { + $first_name = stripslashes($row[$first_column]); + } + + if(isset($row[$last_column])) + { + $last_name = stripslashes($row[$last_column]); + } + + $full_name = $first_name; + + // If we have a first name and we have a last name + if($full_name != "" && $last_name != "") + { + // append a space, then the last name + $full_name .= " ".$last_name; + } + // If we have no first name, but we have a last name + else if($last_name != "") + { + // append the last name without the space. + $full_name .= $last_name; + } + + $log->debug("Exiting return_name method ..."); + return $full_name; +} + +/** Function to return language + * @returns $languages -- languages:: Type string + * +*/ + +function get_languages() +{ + global $log; + $log->debug("Entering get_languages() method ..."); + global $languages; + $log->debug("Exiting get_languages method ..."); + return $languages; +} + +/** Function to return language + * @param $key -- key:: Type string + * @returns $languages -- languages:: Type string + * +*/ + +//seems not used +function get_language_display($key) +{ + global $log; + $log->debug("Entering get_language_display(".$key.") method ..."); + global $languages; + $log->debug("Exiting get_language_display method ..."); + return $languages[$key]; +} + +/** Function returns the user array + * @param $assigned_user_id -- assigned_user_id:: Type string + * @returns $user_list -- user list:: Type array + * +*/ + +function get_assigned_user_name(&$assigned_user_id) +{ + global $log; + $log->debug("Entering get_assigned_user_name(".$assigned_user_id.") method ..."); + $user_list = &get_user_array(false,""); + if(isset($user_list[$assigned_user_id])) + { + $log->debug("Exiting get_assigned_user_name method ..."); + return $user_list[$assigned_user_id]; + } + + $log->debug("Exiting get_assigned_user_name method ..."); + return ""; +} + +/** Function returns the user key in user array + * @param $add_blank -- boolean:: Type boolean + * @param $status -- user status:: Type string + * @param $assigned_user -- user id:: Type string + * @param $private -- sharing type:: Type string + * @returns $user_array -- user array:: Type array + * +*/ + +//used in module file +function get_user_array($add_blank=true, $status="Active", $assigned_user="",$private="") +{ + global $log; + $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); + global $current_user; + if(isset($current_user) && $current_user->id != '') + { + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + } + static $user_array = null; + $module=$_REQUEST['module']; + + if($user_array == null) + { + require_once('include/database/PearDatabase.php'); + $db = PearDatabase::getInstance(); + $temp_result = Array(); + // Including deleted vtiger_users for now. + if (empty($status)) { + $query = "SELECT id, user_name from vtiger_users"; + $params = array(); + } + else { + if($private == 'private') + { + $log->debug("Sharing is Private. Only the current user should be listed"); + $query = "select id as id,user_name as user_name,first_name,last_name from vtiger_users where id=? and status='Active' union select vtiger_user2role.userid as id,vtiger_users.user_name as user_name , + vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name + from vtiger_user2role inner join vtiger_users on vtiger_users.id=vtiger_user2role.userid inner join vtiger_role on vtiger_role.roleid=vtiger_user2role.roleid where vtiger_role.parentrole like ? and status='Active' union + select shareduserid as id,vtiger_users.user_name as user_name , + vtiger_users.first_name as first_name ,vtiger_users.last_name as last_name from vtiger_tmp_write_user_sharing_per inner join vtiger_users on vtiger_users.id=vtiger_tmp_write_user_sharing_per.shareduserid where status='Active' and vtiger_tmp_write_user_sharing_per.userid=? and vtiger_tmp_write_user_sharing_per.tabid=?"; + $params = array($current_user->id, $current_user_parent_role_seq."::%", $current_user->id, getTabid($module)); + } + else + { + $log->debug("Sharing is Public. All vtiger_users should be listed"); + $query = "SELECT id, user_name,first_name,last_name from vtiger_users WHERE status=?"; + $params = array($status); + } + } + if (!empty($assigned_user)) { + $query .= " OR id=?"; + array_push($params, $assigned_user); + } + + $query .= " order by user_name ASC"; + + $result = $db->pquery($query, $params, true, "Error filling in user array: "); + + if ($add_blank==true){ + // Add in a blank row + $temp_result[''] = ''; + } + + // Get the id and the name. + while($row = $db->fetchByAssoc($result)) + { + $temp_result[$row['id']] = getFullNameFromArray('Users', $row); + } + + $user_array = &$temp_result; + } + + $log->debug("Exiting get_user_array method ..."); + + return $user_array; +} + +function get_group_array($add_blank=true, $status="Active", $assigned_user="",$private="") +{ + global $log; + $log->debug("Entering get_user_array(".$add_blank.",". $status.",".$assigned_user.",".$private.") method ..."); + global $current_user; + if(isset($current_user) && $current_user->id != '') + { + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + } + static $group_array = null; + $module=$_REQUEST['module']; + + if($group_array == null) + { + require_once('include/database/PearDatabase.php'); + $db = PearDatabase::getInstance(); + $temp_result = Array(); + // Including deleted vtiger_users for now. + $log->debug("Sharing is Public. All vtiger_users should be listed"); + $query = "SELECT groupid, groupname from vtiger_groups"; + $params = array(); + + if($private == 'private'){ + + $query .= " WHERE groupid=?"; + $params = array( $current_user->id); + + if(count($current_user_groups) != 0) { + $query .= " OR vtiger_groups.groupid in (".generateQuestionMarks($current_user_groups).")"; + array_push($params, $current_user_groups); + } + $log->debug("Sharing is Private. Only the current user should be listed"); + $query .= " union select vtiger_group2role.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_group2role inner join vtiger_groups on vtiger_groups.groupid=vtiger_group2role.groupid inner join vtiger_role on vtiger_role.roleid=vtiger_group2role.roleid where vtiger_role.parentrole like ?"; + array_push($params, $current_user_parent_role_seq."::%"); + + if(count($current_user_groups) != 0) { + $query .= " union select vtiger_groups.groupid as groupid,vtiger_groups.groupname as groupname from vtiger_groups inner join vtiger_group2rs on vtiger_groups.groupid=vtiger_group2rs.groupid where vtiger_group2rs.roleandsubid in (".generateQuestionMarks($parent_roles).")"; + array_push($params, $parent_roles); + } + + $query .= " union select sharedgroupid as groupid,vtiger_groups.groupname as groupname from vtiger_tmp_write_group_sharing_per inner join vtiger_groups on vtiger_groups.groupid=vtiger_tmp_write_group_sharing_per.sharedgroupid where vtiger_tmp_write_group_sharing_per.userid=?"; + array_push($params, $current_user->id); + + $query .= " and vtiger_tmp_write_group_sharing_per.tabid=?"; + array_push($params, getTabid($module)); + } + $query .= " order by groupname ASC"; + + $result = $db->pquery($query, $params, true, "Error filling in user array: "); + + if ($add_blank==true){ + // Add in a blank row + $temp_result[''] = ''; + } + + // Get the id and the name. + while($row = $db->fetchByAssoc($result)) + { + $temp_result[$row['groupid']] = $row['groupname']; + } + + $group_array = &$temp_result; + } + + $log->debug("Exiting get_user_array method ..."); + return $group_array; +} +/** Function skips executing arbitary commands given in a string + * @param $string -- string:: Type string + * @param $maxlength -- maximun length:: Type integer + * @returns $string -- escaped string:: Type string + * +*/ + +function clean($string, $maxLength) +{ + global $log; + $log->debug("Entering clean(".$string.",". $maxLength.") method ..."); + $string = substr($string, 0, $maxLength); + $log->debug("Exiting clean method ..."); + return escapeshellcmd($string); +} + +/** + * Copy the specified request variable to the member variable of the specified object. + * Do no copy if the member variable is already set. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function safe_map($request_var, & $focus, $always_copy = false) +{ + global $log; + $log->debug("Entering safe_map(".$request_var.",".get_class($focus).",".$always_copy.") method ..."); + safe_map_named($request_var, $focus, $request_var, $always_copy); + $log->debug("Exiting safe_map method ..."); +} + +/** + * Copy the specified request variable to the member variable of the specified object. + * Do no copy if the member variable is already set. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function safe_map_named($request_var, & $focus, $member_var, $always_copy) +{ + global $log; + $log->debug("Entering safe_map_named(".$request_var.",".get_class($focus).",".$member_var.",".$always_copy.") method ..."); + if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) { + $log->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var"); + $focus->$member_var = $_REQUEST[$request_var]; + } + $log->debug("Exiting safe_map_named method ..."); +} + +/** This function retrieves an application language file and returns the array of strings included in the $app_list_strings var. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are using the current language, do not call this function unless you are loading it for the first time */ + +function return_app_list_strings_language($language) +{ + global $log; + $log->debug("Entering return_app_list_strings_language(".$language.") method ..."); + global $app_list_strings, $default_language, $log, $translation_string_prefix; + $temp_app_list_strings = $app_list_strings; + $language_used = $language; + + @include("include/language/$language.lang.php"); + if(!isset($app_list_strings)) + { + $log->warn("Unable to find the application language file for language: ".$language); + require("include/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($app_list_strings)) + { + $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_app_list_strings_language method ..."); + return null; + } + + + $return_value = $app_list_strings; + $app_list_strings = $temp_app_list_strings; + + $log->debug("Exiting return_app_list_strings_language method ..."); + return $return_value; +} + +/** + * Retrieve the app_currency_strings for the required language. + */ +function return_app_currency_strings_language($language) { + global $log; + $log->debug("Entering return_app_currency_strings_language(".$language.") method ..."); + global $app_currency_strings, $default_language, $log, $translation_string_prefix; + // Backup the value first + $temp_app_currency_strings = $app_currency_strings; + @include("include/language/$language.lang.php"); + if(!isset($app_currency_strings)) + { + $log->warn("Unable to find the application language file for language: ".$language); + require("include/language/$default_language.lang.php"); + $language_used = $default_language; + } + if(!isset($app_currency_strings)) + { + $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_app_currency_strings_language method ..."); + return null; + } + $return_value = $app_currency_strings; + + // Restore the value back + $app_currency_strings = $temp_app_currency_strings; + + $log->debug("Exiting return_app_currency_strings_language method ..."); + return $return_value; +} + +/** This function retrieves an application language file and returns the array of strings included. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are using the current language, do not call this function unless you are loading it for the first time */ +function return_application_language($language) +{ + global $log; + $log->debug("Entering return_application_language(".$language.") method ..."); + global $app_strings, $default_language, $log, $translation_string_prefix; + $temp_app_strings = $app_strings; + $language_used = $language; + + checkFileAccessForInclusion("include/language/$language.lang.php"); + @include("include/language/$language.lang.php"); + if(!isset($app_strings)) + { + $log->warn("Unable to find the application language file for language: ".$language); + require("include/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($app_strings)) + { + $log->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_application_language method ..."); + return null; + } + + // If we are in debug mode for translating, turn on the prefix now! + if($translation_string_prefix) + { + foreach($app_strings as $entry_key=>$entry_value) + { + $app_strings[$entry_key] = $language_used.' '.$entry_value; + } + } + + $return_value = $app_strings; + $app_strings = $temp_app_strings; + + $log->debug("Exiting return_application_language method ..."); + return $return_value; +} + +/** This function retrieves a module's language file and returns the array of strings included. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are in the current module, do not call this function unless you are loading it for the first time */ +function return_module_language($language, $module) +{ + global $log; + $log->debug("Entering return_module_language(".$language.",". $module.") method ..."); + global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; + static $cachedModuleStrings = array(); + + if(!empty($cachedModuleStrings[$module])) { + $log->debug("Exiting return_module_language method ..."); + return $cachedModuleStrings[$module]; + } + + $temp_mod_strings = $mod_strings; + $language_used = $language; + + @include("modules/$module/language/$language.lang.php"); + if(!isset($mod_strings)) + { + $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); + if($default_language == 'en_us') { + require("modules/$module/language/$default_language.lang.php"); + $language_used = $default_language; + } else { + @include("modules/$module/language/$default_language.lang.php"); + if(!isset($mod_strings)) { + require("modules/$module/language/en_us.lang.php"); + $language_used = 'en_us'; + } else { + $language_used = $default_language; + } + } + } + + if(!isset($mod_strings)) + { + $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_module_language method ..."); + return null; + } + + // If we are in debug mode for translating, turn on the prefix now! + if($translation_string_prefix) + { + foreach($mod_strings as $entry_key=>$entry_value) + { + $mod_strings[$entry_key] = $language_used.' '.$entry_value; + } + } + + $return_value = $mod_strings; + $mod_strings = $temp_mod_strings; + + $log->debug("Exiting return_module_language method ..."); + $cachedModuleStrings[$module] = $return_value; + return $return_value; +} + +/*This function returns the mod_strings for the current language and the specified module +*/ + +function return_specified_module_language($language, $module) +{ + global $log; + global $default_language, $translation_string_prefix; + + @include("modules/$module/language/$language.lang.php"); + if(!isset($mod_strings)) + { + $log->warn("Unable to find the module language file for language: ".$language." and module: ".$module); + require("modules/$module/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($mod_strings)) + { + $log->fatal("Unable to load the module($module) language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_module_language method ..."); + return null; + } + + $return_value = $mod_strings; + + $log->debug("Exiting return_module_language method ..."); + return $return_value; +} + +/** This function retrieves an application language file and returns the array of strings included in the $mod_list_strings var. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + * If you are using the current language, do not call this function unless you are loading it for the first time */ +function return_mod_list_strings_language($language,$module) +{ + global $log; + $log->debug("Entering return_mod_list_strings_language(".$language.",".$module.") method ..."); + global $mod_list_strings, $default_language, $log, $currentModule,$translation_string_prefix; + + $language_used = $language; + $temp_mod_list_strings = $mod_list_strings; + + if($currentModule == $module && isset($mod_list_strings) && $mod_list_strings != null) + { + $log->debug("Exiting return_mod_list_strings_language method ..."); + return $mod_list_strings; + } + + @include("modules/$module/language/$language.lang.php"); + + if(!isset($mod_list_strings)) + { + $log->fatal("Unable to load the application list language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_mod_list_strings_language method ..."); + return null; + } + + $return_value = $mod_list_strings; + $mod_list_strings = $temp_mod_list_strings; + + $log->debug("Exiting return_mod_list_strings_language method ..."); + return $return_value; +} + +/** This function retrieves a theme's language file and returns the array of strings included. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function return_theme_language($language, $theme) +{ + global $log; + $log->debug("Entering return_theme_language(".$language.",". $theme.") method ..."); + global $mod_strings, $default_language, $log, $currentModule, $translation_string_prefix; + + $language_used = $language; + + @include("themes/$theme/language/$current_language.lang.php"); + if(!isset($theme_strings)) + { + $log->warn("Unable to find the theme file for language: ".$language." and theme: ".$theme); + require("themes/$theme/language/$default_language.lang.php"); + $language_used = $default_language; + } + + if(!isset($theme_strings)) + { + $log->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)"); + $log->debug("Exiting return_theme_language method ..."); + return null; + } + + // If we are in debug mode for translating, turn on the prefix now! + if($translation_string_prefix) + { + foreach($theme_strings as $entry_key=>$entry_value) + { + $theme_strings[$entry_key] = $language_used.' '.$entry_value; + } + } + + $log->debug("Exiting return_theme_language method ..."); + return $theme_strings; +} + + + +/** If the session variable is defined and is not equal to "" then return it. Otherwise, return the default value. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. +*/ +function return_session_value_or_default($varname, $default) +{ + global $log; + $log->debug("Entering return_session_value_or_default(".$varname.",". $default.") method ..."); + if(isset($_SESSION[$varname]) && $_SESSION[$varname] != "") + { + $log->debug("Exiting return_session_value_or_default method ..."); + return $_SESSION[$varname]; + } + + $log->debug("Exiting return_session_value_or_default method ..."); + return $default; +} + +/** + * Creates an array of where restrictions. These are used to construct a where SQL statement on the query + * It looks for the variable in the $_REQUEST array. If it is set and is not "" it will create a where clause out of it. + * @param &$where_clauses - The array to append the clause to + * @param $variable_name - The name of the variable to look for an add to the where clause if found + * @param $SQL_name - [Optional] If specified, this is the SQL column name that is used. If not specified, the $variable_name is used as the SQL_name. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function append_where_clause(&$where_clauses, $variable_name, $SQL_name = null) +{ + global $log; + $log->debug("Entering append_where_clause(".$where_clauses.",".$variable_name.",".$SQL_name.") method ..."); + if($SQL_name == null) + { + $SQL_name = $variable_name; + } + + if(isset($_REQUEST[$variable_name]) && $_REQUEST[$variable_name] != "") + { + array_push($where_clauses, "$SQL_name like '$_REQUEST[$variable_name]%'"); + } + $log->debug("Exiting append_where_clause method ..."); +} + +/** + * Generate the appropriate SQL based on the where clauses. + * @param $where_clauses - An Array of individual where clauses stored as strings + * @returns string where_clause - The final SQL where clause to be executed. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function generate_where_statement($where_clauses) +{ + global $log; + $log->debug("Entering generate_where_statement(".$where_clauses.") method ..."); + $where = ""; + foreach($where_clauses as $clause) + { + if($where != "") + $where .= " and "; + $where .= $clause; + } + + $log->info("Here is the where clause for the list view: $where"); + $log->debug("Exiting generate_where_statement method ..."); + return $where; +} + +/** + * A temporary method of generating GUIDs of the correct format for our DB. + * @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee + * + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. +*/ +function create_guid() +{ + global $log; + $log->debug("Entering create_guid() method ..."); + $microTime = microtime(); + list($a_dec, $a_sec) = explode(" ", $microTime); + + $dec_hex = sprintf("%x", $a_dec* 1000000); + $sec_hex = sprintf("%x", $a_sec); + + ensure_length($dec_hex, 5); + ensure_length($sec_hex, 6); + + $guid = ""; + $guid .= $dec_hex; + $guid .= create_guid_section(3); + $guid .= '-'; + $guid .= create_guid_section(4); + $guid .= '-'; + $guid .= create_guid_section(4); + $guid .= '-'; + $guid .= create_guid_section(4); + $guid .= '-'; + $guid .= $sec_hex; + $guid .= create_guid_section(6); + + $log->debug("Exiting create_guid method ..."); + return $guid; + +} + +/** Function to create guid section for a given character + * @param $characters -- characters:: Type string + * @returns $return -- integer:: Type integer`` + */ +function create_guid_section($characters) +{ + global $log; + $log->debug("Entering create_guid_section(".$characters.") method ..."); + $return = ""; + for($i=0; $i<$characters; $i++) + { + $return .= sprintf("%x", rand(0,15)); + } + $log->debug("Exiting create_guid_section method ..."); + return $return; +} + +/** Function to ensure length + * @param $string -- string:: Type string + * @param $length -- length:: Type string + */ + +function ensure_length(&$string, $length) +{ + global $log; + $log->debug("Entering ensure_length(".$string.",". $length.") method ..."); + $strlen = strlen($string); + if($strlen < $length) + { + $string = str_pad($string,$length,"0"); + } + else if($strlen > $length) + { + $string = substr($string, 0, $length); + } + $log->debug("Exiting ensure_length method ..."); +} +/* +function microtime_diff($a, $b) { + global $log; + $log->debug("Entering microtime_diff(".$a.",". $b.") method ..."); + list($a_dec, $a_sec) = explode(" ", $a); + list($b_dec, $b_sec) = explode(" ", $b); + $log->debug("Exiting microtime_diff method ..."); + return $b_sec - $a_sec + $b_dec - $a_dec; +} + */ + +/** + * Return the display name for a theme if it exists. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_theme_display($theme) { + global $log; + $log->debug("Entering get_theme_display(".$theme.") method ..."); + global $theme_name, $theme_description; + $temp_theme_name = $theme_name; + $temp_theme_description = $theme_description; + + if (is_file("./themes/$theme/config.php")) { + @include("./themes/$theme/config.php"); + $return_theme_value = $theme_name; + } + else { + $return_theme_value = $theme; + } + $theme_name = $temp_theme_name; + $theme_description = $temp_theme_description; + + $log->debug("Exiting get_theme_display method ..."); + return $return_theme_value; +} + +/** + * Return an array of directory names. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_themes() { + global $log; + $log->debug("Entering get_themes() method ..."); + if ($dir = @opendir("./themes")) { + while (($file = readdir($dir)) !== false) { + if ($file != ".." && $file != "." && $file != "CVS" && $file != "Attic" && $file != "akodarkgem" && $file != "bushtree" && $file != "coolblue" && $file != "Amazon" && $file != "busthree" && $file != "Aqua" && $file != "nature" && $file != "orange" && $file != "blue") { + if(is_dir("./themes/".$file)) { + if(!($file[0] == '.')) { + // set the initial theme name to the filename + $name = $file; + + // if there is a configuration class, load that. + if(is_file("./themes/$file/config.php")) + { + require_once("./themes/$file/config.php"); + } + + if(is_file("./themes/$file/style.css")) + { + $filelist[$file] = $name; + } + } + } + } + } + closedir($dir); + } + + ksort($filelist); + $log->debug("Exiting get_themes method ..."); + return $filelist; +} + + + +/** + * Create javascript to clear values of all elements in a form. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_clear_form_js () { +global $log; +$log->debug("Entering get_clear_form_js () method ..."); +$the_script = << + + +EOQ; + +$log->debug("Exiting get_clear_form_js method ..."); +return $the_script; +} + +/** + * Create javascript to set the cursor focus to specific vtiger_field in a form + * when the screen is rendered. The vtiger_field name is currently hardcoded into the + * the function. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_set_focus_js () { +global $log; +$log->debug("Entering set_focus() method ..."); +//TODO Clint 5/20 - Make this function more generic so that it can take in the target form and vtiger_field names as variables +$the_script = << + + +EOQ; + +$log->debug("Exiting get_set_focus_js method ..."); +return $the_script; +} + +/** + * Very cool algorithm for sorting multi-dimensional arrays. Found at http://us2.php.net/manual/en/function.array-multisort.php + * Syntax: $new_array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...); + * Explanation: $array is the array you want to sort, 'col1' is the name of the column + * you want to sort, SORT_FLAGS are : SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING + * you can repeat the 'col',FLAG,FLAG, as often you want, the highest prioritiy is given to + * the first - so the array is sorted by the last given column first, then the one before ... + * Example: $array = array_csort($array,'town','age',SORT_DESC,'name'); + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function array_csort() { + global $log; + $log->debug("Entering array_csort() method ..."); + $args = func_get_args(); + $marray = array_shift($args); + $i = 0; + + $msortline = "return(array_multisort("; + foreach ($args as $arg) { + $i++; + if (is_string($arg)) { + foreach ($marray as $row) { + $sortarr[$i][] = $row[$arg]; + } + } else { + $sortarr[$i] = $arg; + } + $msortline .= "\$sortarr[".$i."],"; + } + $msortline .= "\$marray));"; + + eval($msortline); + $log->debug("Exiting array_csort method ..."); + return $marray; +} + +/** Function to set default varibles on to the global variable + * @param $defaults -- default values:: Type array + */ +function set_default_config(&$defaults) +{ + global $log; + $log->debug("Entering set_default_config(".$defaults.") method ..."); + + foreach ($defaults as $name=>$value) + { + if ( ! isset($GLOBALS[$name]) ) + { + $GLOBALS[$name] = $value; + } + } + $log->debug("Exiting set_default_config method ..."); +} + +$toHtml = array( + '"' => '"', + '<' => '<', + '>' => '>', + '& ' => '& ', + "'" => ''', + '' => '\r', + '\r\n'=>'\n', + +); + +/** Function to convert the given string to html + * @param $string -- string:: Type string + * @param $ecnode -- boolean:: Type boolean + * @returns $string -- string:: Type string + * + */ +function to_html($string, $encode=true) +{ + global $log,$default_charset; + //$log->debug("Entering to_html(".$string.",".$encode.") method ..."); + global $toHtml; + $action = vtlib_purify($_REQUEST['action']); + $search = vtlib_purify($_REQUEST['search']); + + $doconvert = false; + + if($_REQUEST['module'] != 'Settings' && $_REQUEST['file'] != 'ListView' && $_REQUEST['module'] != 'Portal' && $_REQUEST['module'] != "Reports")// && $_REQUEST['module'] != 'Emails') + $ajax_action = $_REQUEST['module'].'Ajax'; + + if(is_string($string)) + { + if($action != 'CustomView' && $action != 'Export' && $action != $ajax_action && $action != 'LeadConvertToEntities' && $action != 'CreatePDF' && $action != 'ConvertAsFAQ' && $_REQUEST['module'] != 'Dashboard' && $action != 'CreateSOPDF' && $action != 'SendPDFMail' && (!isset($_REQUEST['submode'])) ) + { + $doconvert = true; + } + else if($search == true) + { + // Fix for tickets #4647, #4648. Conversion required in case of search results also. + $doconvert = true; + } + if ($doconvert == true) + { + if(strtolower($default_charset) == 'utf-8') + $string = htmlentities($string, ENT_QUOTES, $default_charset); + else + $string = preg_replace(array('//', '/"/'), array('<', '>', '"'), $string); + } + } + + //$log->debug("Exiting to_html method ..."); + return $string; +} + +/** Function to get the tablabel for a given id + * @param $tabid -- tab id:: Type integer + * @returns $string -- string:: Type string +*/ + +function getTabname($tabid) +{ + global $log; + $log->debug("Entering getTabname(".$tabid.") method ..."); + $log->info("tab id is ".$tabid); + global $adb; + $sql = "select tablabel from vtiger_tab where tabid=?"; + $result = $adb->pquery($sql, array($tabid)); + $tabname= $adb->query_result($result,0,"tablabel"); + $log->debug("Exiting getTabname method ..."); + return $tabname; + +} + +/** Function to get the tab module name for a given id + * @param $tabid -- tab id:: Type integer + * @returns $string -- string:: Type string + * + */ + +function getTabModuleName($tabid) +{ + global $log; + $log->debug("Entering getTabModuleName(".$tabid.") method ..."); + + // Lookup information in cache first + $tabname = VTCacheUtils::lookupModulename($tabid); + if($tabname === false) { + if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) { + include('tabdata.php'); + $tabname = array_search($tabid,$tab_info_array); + + if($tabname == false) { + global $adb; + $sql = "select name from vtiger_tab where tabid=?"; + $result = $adb->pquery($sql, array($tabid)); + $tabname= $adb->query_result($result,0,"name"); + } + + // Update information to cache for re-use + VTCacheUtils::updateTabidInfo($tabid, $tabname); + + } else { + $log->info("tab id is ".$tabid); + global $adb; + $sql = "select name from vtiger_tab where tabid=?"; + $result = $adb->pquery($sql, array($tabid)); + $tabname= $adb->query_result($result,0,"name"); + + // Update information to cache for re-use + VTCacheUtils::updateTabidInfo($tabid, $tabname); + } + } + $log->debug("Exiting getTabModuleName method ..."); + return $tabname; +} + +/** Function to get column fields for a given module + * @param $module -- module:: Type string + * @returns $column_fld -- column field :: Type array + * + */ + +function getColumnFields($module) +{ + global $log; + $log->debug("Entering getColumnFields(".$module.") method ..."); + $log->debug("in getColumnFields ".$module); + + // Lookup in cache for information + $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); + + if($cachedModuleFields === false) { + global $adb; + $tabid = getTabid($module); + if ($module == 'Calendar') { + $tabid = array('9','16'); + } + + // Let us pick up all the fields first so that we can cache information + $sql = "SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence + FROM vtiger_field WHERE tabid in (" . generateQuestionMarks($tabid) . ")"; + + $result = $adb->pquery($sql, array($tabid)); + $noofrows = $adb->num_rows($result); + + if($noofrows) { + while($resultrow = $adb->fetch_array($result)) { + // Update information to cache for re-use + VTCacheUtils::updateFieldInfo( + $resultrow['tabid'], $resultrow['fieldname'], $resultrow['fieldid'], + $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], + $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence'] + ); + } + } + + // For consistency get information from cache + $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); + } + + if($module == 'Calendar') { + $cachedEventsFields = VTCacheUtils::lookupFieldInfo_Module('Events'); + if($cachedModuleFields == false) $cachedModuleFields = $cachedEventsFields; + else $cachedModuleFields = array_merge($cachedModuleFields, $cachedEventsFields); + } + + $column_fld = array(); + if($cachedModuleFields) { + foreach($cachedModuleFields as $fieldinfo) { + $column_fld[$fieldinfo['fieldname']] = ''; + } + } + + $log->debug("Exiting getColumnFields method ..."); + return $column_fld; +} + +/** Function to get a users's mail id + * @param $userid -- userid :: Type integer + * @returns $email -- email :: Type string + * + */ + +function getUserEmail($userid) +{ + global $log; + $log->debug("Entering getUserEmail(".$userid.") method ..."); + $log->info("in getUserEmail ".$userid); + + global $adb; + if($userid != '') + { + $sql = "select email1 from vtiger_users where id=?"; + $result = $adb->pquery($sql, array($userid)); + $email = $adb->query_result($result,0,"email1"); + } + $log->debug("Exiting getUserEmail method ..."); + return $email; +} + +/** Function to get a userid for outlook + * @param $username -- username :: Type string + * @returns $user_id -- user id :: Type integer + */ + +//outlook security +function getUserId_Ol($username) +{ + global $log; + $log->debug("Entering getUserId_Ol(".$username.") method ..."); + $log->info("in getUserId_Ol ".$username); + + global $adb; + $sql = "select id from vtiger_users where user_name=?"; + $result = $adb->pquery($sql, array($username)); + $num_rows = $adb->num_rows($result); + if($num_rows > 0) + { + $user_id = $adb->query_result($result,0,"id"); + } + else + { + $user_id = 0; + } + $log->debug("Exiting getUserId_Ol method ..."); + return $user_id; +} + + +/** Function to get a action id for a given action name + * @param $action -- action name :: Type string + * @returns $actionid -- action id :: Type integer + */ + +//outlook security + +function getActionid($action) +{ + global $log; + $log->debug("Entering getActionid(".$action.") method ..."); + global $adb; + $log->info("get Actionid ".$action); + $actionid = ''; + if(file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) + { + include('tabdata.php'); + $actionid= $action_id_array[$action]; + } + else + { + $query="select * from vtiger_actionmapping where actionname=?"; + $result =$adb->pquery($query, array($action)); + $actionid=$adb->query_result($result,0,'actionid'); + + } + $log->info("action id selected is ".$actionid ); + $log->debug("Exiting getActionid method ..."); + return $actionid; +} + +/** Function to get a action for a given action id + * @param $action id -- action id :: Type integer + * @returns $actionname-- action name :: Type string + */ + + +function getActionname($actionid) +{ + global $log; + $log->debug("Entering getActionname(".$actionid.") method ..."); + global $adb; + + $actionname=''; + + if (file_exists('tabdata.php') && (filesize('tabdata.php') != 0)) + { + include('tabdata.php'); + $actionname= $action_name_array[$actionid]; + } + else + { + + $query="select * from vtiger_actionmapping where actionid=? and securitycheck=0"; + $result =$adb->pquery($query, array($actionid)); + $actionname=$adb->query_result($result,0,"actionname"); + } + $log->debug("Exiting getActionname method ..."); + return $actionname; +} + +/** Function to get a assigned user id for a given entity + * @param $record -- entity id :: Type integer + * @returns $user_id -- user id :: Type integer + */ + +function getUserId($record) +{ + global $log; + $log->debug("Entering getUserId(".$record.") method ..."); + $log->info("in getUserId ".$record); + + global $adb; + $user_id=$adb->query_result($adb->pquery("select * from vtiger_crmentity where crmid = ?", array($record)),0,'smownerid'); + $log->debug("Exiting getUserId method ..."); + return $user_id; +} + +/** Function to get a user id or group id for a given entity + * @param $record -- entity id :: Type integer + * @returns $ownerArr -- owner id :: Type array + */ + +function getRecordOwnerId($record) +{ + global $log; + $log->debug("Entering getRecordOwnerId(".$record.") method ..."); + global $adb; + $ownerArr=Array(); + $query="select smownerid from vtiger_crmentity where crmid = ?"; + $result=$adb->pquery($query, array($record)); + if($adb->num_rows($result) > 0) + { + $ownerId=$adb->query_result($result,0,'smownerid'); + $sql_result = $adb->pquery("select count(*) as count from vtiger_users where id = ?",array($ownerId)); + if($adb->query_result($sql_result,0,'count') > 0) + $ownerArr['Users'] = $ownerId; + else + $ownerArr['Groups'] = $ownerId; + } + $log->debug("Exiting getRecordOwnerId method ..."); + return $ownerArr; + +} + +/** Function to insert value to profile2field table + * @param $profileid -- profileid :: Type integer + */ + + +function insertProfile2field($profileid) +{ + global $log; + $log->debug("Entering insertProfile2field(".$profileid.") method ..."); + $log->info("in insertProfile2field ".$profileid); + + global $adb; + $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); + $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); + $num_rows = $adb->num_rows($fld_result); + for($i=0; $i<$num_rows; $i++) { + $tab_id = $adb->query_result($fld_result,$i,'tabid'); + $field_id = $adb->query_result($fld_result,$i,'fieldid'); + $params = array($profileid, $tab_id, $field_id, 0, 0); + $adb->pquery("insert into vtiger_profile2field values (?,?,?,?,?)", $params); + } + $log->debug("Exiting insertProfile2field method ..."); +} + +/** Function to insert into default org field + */ + +function insert_def_org_field() +{ + global $log; + $log->debug("Entering insert_def_org_field() method ..."); + global $adb; + $adb->database->SetFetchMode(ADODB_FETCH_ASSOC); + $fld_result = $adb->pquery("select * from vtiger_field where generatedtype=1 and displaytype in (1,2,3) and vtiger_field.presence in (0,2) and tabid != 29", array()); + $num_rows = $adb->num_rows($fld_result); + for($i=0; $i<$num_rows; $i++) + { + $tab_id = $adb->query_result($fld_result,$i,'tabid'); + $field_id = $adb->query_result($fld_result,$i,'fieldid'); + $params = array($tab_id, $field_id, 0, 0); + $adb->pquery("insert into vtiger_def_org_field values (?,?,?,?)", $params); + } + $log->debug("Exiting insert_def_org_field() method ..."); +} + +/** Function to insert value to profile2field table + * @param $fld_module -- field module :: Type string + * @param $profileid -- profileid :: Type integer + * @returns $result -- result :: Type string + */ + +function getProfile2FieldList($fld_module, $profileid) +{ + global $log; + $log->debug("Entering getProfile2FieldList(".$fld_module.",". $profileid.") method ..."); + $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); + + global $adb; + $tabid = getTabid($fld_module); + + $query = "select vtiger_profile2field.visible,vtiger_field.* from vtiger_profile2field inner join vtiger_field on vtiger_field.fieldid=vtiger_profile2field.fieldid where vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,1,2)"; + $result = $adb->pquery($query, array($profileid, $tabid)); + $log->debug("Exiting getProfile2FieldList method ..."); + return $result; +} + +/** Function to insert value to profile2fieldPermissions table + * @param $fld_module -- field module :: Type string + * @param $profileid -- profileid :: Type integer + * @returns $return_data -- return_data :: Type string + */ + +//added by jeri + +function getProfile2FieldPermissionList($fld_module, $profileid) +{ + global $log; + $log->debug("Entering getProfile2FieldPermissionList(".$fld_module.",". $profileid.") method ..."); + $log->info("in getProfile2FieldList ".$fld_module. ' vtiger_profile id is '.$profileid); + + // Cache information to re-use + static $_module_fieldpermission_cache = array(); + + if(!isset($_module_fieldpermission_cache[$fld_module])) { + $_module_fieldpermission_cache[$fld_module] = array(); + } + + // Lookup cache first + $return_data = VTCacheUtils::lookupProfile2FieldPermissionList($fld_module, $profileid); + + if($return_data === false) { + + $return_data = array(); + + global $adb; + $tabid = getTabid($fld_module); + + $query = "SELECT vtiger_profile2field.visible, vtiger_profile2field.readonly, vtiger_field.fieldlabel, vtiger_field.uitype, + vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata + FROM vtiger_profile2field INNER JOIN vtiger_field ON vtiger_field.fieldid=vtiger_profile2field.fieldid + WHERE vtiger_profile2field.profileid=? and vtiger_profile2field.tabid=? and vtiger_field.presence in (0,2)"; + + $qparams = array($profileid, $tabid); + $result = $adb->pquery($query, $qparams); + + for($i=0; $i<$adb->num_rows($result); $i++) { + $return_data[]=array( + $adb->query_result($result,$i,"fieldlabel"), + $adb->query_result($result,$i,"visible"), // From vtiger_profile2field.visible + $adb->query_result($result,$i,"uitype"), + $adb->query_result($result,$i,"readonly"), + $adb->query_result($result,$i,"fieldid"), + $adb->query_result($result,$i,"displaytype"), + $adb->query_result($result,$i,"typeofdata") + ); + } + + // Update information to cache for re-use + VTCacheUtils::updateProfile2FieldPermissionList($fld_module, $profileid, $return_data); + } + + + $log->debug("Exiting getProfile2FieldPermissionList method ..."); + return $return_data; +} + + +/** Function to insert value to profile2fieldPermissions table + * @param $fld_module -- field module :: Type string + * @param $profileid -- profileid :: Type integer + * @returns $return_data -- return_data :: Type string + */ + +function getProfile2ModuleFieldPermissionList($fld_module, $profileid) { + global $log; + $log->debug("Entering getProfile2ModuleFieldPermissionList(".$fld_module.",". $profileid.") method ..."); + $log->info("in getProfile2ModuleFieldList ".$fld_module. ' vtiger_profile id is '.$profileid); + + // Cache information to re-use + static $_module_fieldpermission_cache = array(); + + if(!isset($_module_fieldpermission_cache[$fld_module])) { + $_module_fieldpermission_cache[$fld_module] = array(); + } + + $return_data = array(); + + global $adb; + $tabid = getTabid($fld_module); + + $query = "SELECT vtiger_profile2tab.tabid, vtiger_profile2tab.permissions, vtiger_field.fieldlabel, vtiger_field.uitype, + vtiger_field.fieldid, vtiger_field.displaytype, vtiger_field.typeofdata + FROM vtiger_profile2tab INNER JOIN vtiger_field ON vtiger_field.tabid=vtiger_profile2tab.tabid + WHERE vtiger_profile2tab.profileid=? AND vtiger_profile2tab.tabid=? AND vtiger_field.presence in (0,2)"; + $qparams = array($profileid, $tabid); + $result = $adb->pquery($query, $qparams); + + for($i=0; $i<$adb->num_rows($result); $i++) { + $fieldid = $adb->query_result($result,$i,"fieldid"); + $checkentry = $adb->pquery("SELECT 1 FROM vtiger_profile2field WHERE profileid=? AND tabid=? AND fieldid =?",array($profileid,$tabid,$fieldid)); + $visible_value = 0; + $readOnlyValue = 0; + if($adb->num_rows($checkentry) == 0) { + $sql11="INSERT INTO vtiger_profile2field VALUES(?,?,?,?,?)"; + $adb->pquery($sql11, array($profileid, $tabid, $fieldid,$visible_value, $readOnlyValue)); + } + + $sql = "SELECT vtiger_profile2field.visible, vtiger_profile2field.readonly FROM vtiger_profile2field WHERE fieldid=? AND tabid=? AND profileid=?"; + $params = array($fieldid,$tabid,$profileid); + $res = $adb->pquery($sql, $params); + + $return_data[]=array( + $adb->query_result($result,$i,"fieldlabel"), + $adb->query_result($res,0,"visible"), // From vtiger_profile2field.visible + $adb->query_result($result,$i,"uitype"), + $adb->query_result($res,0,"readonly"), // From vtiger_profile2field.readonly + $adb->query_result($result,$i,"fieldid"), + $adb->query_result($result,$i,"displaytype"), + $adb->query_result($result,$i,"typeofdata") + ); + } + + $log->debug("Exiting getProfile2ModuleFieldPermissionList method ..."); + return $return_data; +} + +/** Function to getProfile2allfieldsListinsert value to profile2fieldPermissions table + * @param $mod_array -- mod_array :: Type string + * @param $profileid -- profileid :: Type integer + * @returns $profilelist -- profilelist :: Type string + */ + +function getProfile2AllFieldList($mod_array,$profileid) +{ + global $log; + $log->debug("Entering getProfile2AllFieldList(".$mod_array.",".$profileid.") method ..."); + $log->info("in getProfile2AllFieldList vtiger_profile id is " .$profileid); + + global $adb; + $profilelist=array(); + for($i=0;$idebug("Exiting getProfile2AllFieldList method ..."); + return $profilelist; +} + +/** Function to getdefaultfield organisation list for a given module + * @param $fld_module -- module name :: Type string + * @returns $result -- string :: Type object + */ + +//end of fn added by jeri + +function getDefOrgFieldList($fld_module) +{ + global $log; + $log->debug("Entering getDefOrgFieldList(".$fld_module.") method ..."); + $log->info("in getDefOrgFieldList ".$fld_module); + + global $adb; + $tabid = getTabid($fld_module); + + $query = "select vtiger_def_org_field.visible,vtiger_field.* from vtiger_def_org_field inner join vtiger_field on vtiger_field.fieldid=vtiger_def_org_field.fieldid where vtiger_def_org_field.tabid=? and vtiger_field.presence in (0,2)"; + $qparams = array($tabid); + $result = $adb->pquery($query, $qparams); + $log->debug("Exiting getDefOrgFieldList method ..."); + return $result; +} + +/** Function to getQuickCreate for a given tabid + * @param $tabid -- tab id :: Type string + * @param $actionid -- action id :: Type integer + * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean + */ + +function getQuickCreate($tabid,$actionid) +{ + global $log; + $log->debug("Entering getQuickCreate(".$tabid.",".$actionid.") method ..."); + $module=getTabModuleName($tabid); + $actionname=getActionname($actionid); + $QuickCreateForm= 'true'; + + $perr=isPermitted($module,$actionname); + if($perr == 'no') + { + $QuickCreateForm= 'false'; + } + $log->debug("Exiting getQuickCreate method ..."); + return $QuickCreateForm; + +} + +/** Function to getQuickCreate for a given tabid + * @param $tabid -- tab id :: Type string + * @param $actionid -- action id :: Type integer + * @returns $QuickCreateForm -- QuickCreateForm :: Type boolean + */ + +function ChangeStatus($status,$activityid,$activity_mode='') + { + global $log; + $log->debug("Entering ChangeStatus(".$status.",".$activityid.",".$activity_mode."='') method ..."); + $log->info("in ChangeStatus ".$status. ' vtiger_activityid is '.$activityid); + + global $adb; + if ($activity_mode == 'Task') + { + $query = "Update vtiger_activity set status=? where activityid = ?"; + } + elseif ($activity_mode == 'Events') + { + $query = "Update vtiger_activity set eventstatus=? where activityid = ?"; + } + if($query) { + $adb->pquery($query, array($status, $activityid)); + } + $log->debug("Exiting ChangeStatus method ..."); + } + +/** Function to get unitprice for a given product id + * @param $productid -- product id :: Type integer + * @returns $up -- up :: Type string + */ + +function getUnitPrice($productid, $module='Products') +{ + global $log, $adb; + $log->debug("Entering getUnitPrice($productid,$module) method ..."); + + if($module == 'Services') { + $query = "select unit_price from vtiger_service where serviceid=?"; + } else { + $query = "select unit_price from vtiger_products where productid=?"; + } + $result = $adb->pquery($query, array($productid)); + $unitpice = $adb->query_result($result,0,'unit_price'); + $log->debug("Exiting getUnitPrice method ..."); + return $unitpice; +} + +/** Function to upload product image file + * @param $mode -- mode :: Type string + * @param $id -- id :: Type integer + * @returns $ret_array -- return array:: Type array + */ + +function upload_product_image_file($mode,$id) +{ + global $log; + $log->debug("Entering upload_product_image_file(".$mode.",".$id.") method ..."); + global $root_directory; + $log->debug("Inside upload_product_image_file. The id is ".$id); + $uploaddir = $root_directory ."/test/product/"; + + $file_path_name = $_FILES['imagename']['name']; + if (isset($_REQUEST['imagename_hidden'])) { + $file_name = $_REQUEST['imagename_hidden']; + } else { + //allowed file pathname like UTF-8 Character + $file_name = ltrim(basename(" ".$file_path_name)); // basename($file_path_name); + } + $file_name = $id.'_'.$file_name; + $filetype= $_FILES['imagename']['type']; + $filesize = $_FILES['imagename']['size']; + + $ret_array = Array(); + + if($filesize > 0) + { + + if(move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$file_name)) + { + + $upload_status = "yes"; + $ret_array["status"] = $upload_status; + $ret_array["file_name"] = $file_name; + + + } + else + { + $errorCode = $_FILES['imagename']['error']; + $upload_status = "no"; + $ret_array["status"] = $upload_status; + $ret_array["errorcode"] = $errorCode; + + + } + + } + else + { + $upload_status = "no"; + $ret_array["status"] = $upload_status; + } + $log->debug("Exiting upload_product_image_file method ..."); + return $ret_array; + +} + +/** Function to upload product image file + * @param $id -- id :: Type integer + * @param $deleted_array -- images to be deleted :: Type array + * @returns $imagename -- imagelist:: Type array + */ + +function getProductImageName($id,$deleted_array='') +{ + global $log; + $log->debug("Entering getProductImageName(".$id.",".$deleted_array."='') method ..."); + global $adb; + $image_array=array(); + $query = "select imagename from vtiger_products where productid=?"; + $result = $adb->pquery($query, array($id)); + $image_name = $adb->query_result($result,0,"imagename"); + $image_array=explode("###",$image_name); + $log->debug("Inside getProductImageName. The image_name is ".$image_name); + if($deleted_array!='') + { + $resultant_image = array(); + $resultant_image=array_merge(array_diff($image_array,$deleted_array)); + $imagelists=implode('###',$resultant_image); + $log->debug("Exiting getProductImageName method ..."); + return $imagelists; + } + else + { + $log->debug("Exiting getProductImageName method ..."); + return $image_name; + } +} + +/** Function to get Contact images + * @param $id -- id :: Type integer + * @returns $imagename -- imagename:: Type string + */ + +function getContactImageName($id) +{ + global $log; + $log->debug("Entering getContactImageName(".$id.") method ..."); + global $adb; + $query = "select imagename from vtiger_contactdetails where contactid=?"; + $result = $adb->pquery($query, array($id)); + $image_name = $adb->query_result($result,0,"imagename"); + $log->debug("Inside getContactImageName. The image_name is ".$image_name); + $log->debug("Exiting getContactImageName method ..."); + return $image_name; + +} + +/** Function to update sub total in inventory + * @param $module -- module name :: Type string + * @param $tablename -- tablename :: Type string + * @param $colname -- colname :: Type string + * @param $colname1 -- coluname1 :: Type string + * @param $entid_fld -- entity field :: Type string + * @param $entid -- entid :: Type integer + * @param $prod_total -- totalproduct :: Type integer + */ + +function updateSubTotal($module,$tablename,$colname,$colname1,$entid_fld,$entid,$prod_total) +{ + global $log; + $log->debug("Entering updateSubTotal(".$module.",".$tablename.",".$colname.",".$colname1.",".$entid_fld.",".$entid.",".$prod_total.") method ..."); + global $adb; + //getting the subtotal + $query = "select ".$colname.",".$colname1." from ".$tablename." where ".$entid_fld."=?"; + $result1 = $adb->pquery($query, array($entid)); + $subtot = $adb->query_result($result1,0,$colname); + $subtot_upd = $subtot - $prod_total; + + $gdtot = $adb->query_result($result1,0,$colname1); + $gdtot_upd = $gdtot - $prod_total; + + //updating the subtotal + $sub_query = "update $tablename set $colname=?, $colname1=? where $entid_fld=?"; + $adb->pquery($sub_query, array($subtot_upd, $gdtot_upd, $entid)); + $log->debug("Exiting updateSubTotal method ..."); +} + +/** Function to get Inventory Total + * @param $return_module -- return module :: Type string + * @param $id -- entity id :: Type integer + * @returns $total -- total:: Type integer + */ + +function getInventoryTotal($return_module,$id) +{ + global $log; + $log->debug("Entering getInventoryTotal(".$return_module.",".$id.") method ..."); + global $adb; + if($return_module == "Potentials") + { + $query ="select vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_seproductsrel.* from vtiger_products inner join vtiger_seproductsrel on vtiger_seproductsrel.productid=vtiger_products.productid where crmid=?"; + } + elseif($return_module == "Products") + { + $query="select vtiger_products.productid,vtiger_products.productname,vtiger_products.unit_price,vtiger_products.qtyinstock,vtiger_crmentity.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and productid=?"; + } + $result = $adb->pquery($query, array($id)); + $num_rows=$adb->num_rows($result); + $total=0; + for($i=1;$i<=$num_rows;$i++) + { + $unitprice=$adb->query_result($result,$i-1,'unit_price'); + $qty=$adb->query_result($result,$i-1,'quantity'); + $listprice=$adb->query_result($result,$i-1,'listprice'); + if($listprice == '') + $listprice = $unitprice; + if($qty =='') + $qty = 1; + $total = $total+($qty*$listprice); + } + $log->debug("Exiting getInventoryTotal method ..."); + return $total; +} + +/** Function to update product quantity + * @param $product_id -- product id :: Type integer + * @param $upd_qty -- quantity :: Type integer + */ + +function updateProductQty($product_id, $upd_qty) +{ + global $log; + $log->debug("Entering updateProductQty(".$product_id.",". $upd_qty.") method ..."); + global $adb; + $query= "update vtiger_products set qtyinstock=? where productid=?"; + $adb->pquery($query, array($upd_qty, $product_id)); + $log->debug("Exiting updateProductQty method ..."); + +} + +/** Function to get account information + * @param $parent_id -- parent id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function get_account_info($parent_id) +{ + global $log; + $log->debug("Entering get_account_info(".$parent_id.") method ..."); + global $adb; + $query = "select related_to from vtiger_potential where potentialid=?"; + $result = $adb->pquery($query, array($parent_id)); + $accountid=$adb->query_result($result,0,'related_to'); + $log->debug("Exiting get_account_info method ..."); + return $accountid; +} + +/** Function to get quick create form fields + * @param $fieldlabel -- field label :: Type string + * @param $uitype -- uitype :: Type integer + * @param $fieldname -- field name :: Type string + * @param $tabid -- tabid :: Type integer + * @returns $return_field -- return field:: Type string + */ + +//for Quickcreate-Form + +function get_quickcreate_form($fieldlabel,$uitype,$fieldname,$tabid) +{ + global $log; + $log->debug("Entering get_quickcreate_form(".$fieldlabel.",".$uitype.",".$fieldname.",".$tabid.") method ..."); + $return_field =''; + switch($uitype) + { + case 1: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 2: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 6: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 11: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 13: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 15: $return_field .=get_textcomboField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 16: $return_field .=get_textcomboField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 17: $return_field .=get_textwebField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 19: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 22: $return_field .=get_textmanField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 23: $return_field .=get_textdateField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 50: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 51: $return_field .=get_textaccField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 55: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 63: $return_field .=get_textdurationField($fieldlabel,$fieldname,$tabid); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + case 71: $return_field .=get_textField($fieldlabel,$fieldname); + $log->debug("Exiting get_quickcreate_form method ..."); + return $return_field; + break; + } +} + +/** Function to get quick create form fields + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @param $tid -- tabid :: Type integer + * @returns $form_field -- return field:: Type string + */ + +function get_textmanField($label,$name,$tid) +{ + global $log; + $log->debug("Entering get_textmanField(".$label.",".$name.",".$tid.") method ..."); + $form_field=''; + if($tid == 9) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textmanField method ..."); + return $form_field; + } + if($tid == 16) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textmanField method ..."); + return $form_field; + } + else + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textmanField method ..."); + return $form_field; + } + +} + +/** Function to get textfield for website field + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @returns $form_field -- return field:: Type string + */ + +function get_textwebField($label,$name) +{ + global $log; + $log->debug("Entering get_textwebField(".$label.",".$name.") method ..."); + + $form_field=''; + $form_field .=''; + $form_field .= $label.':
http://
'; + $form_field .=''; + $log->debug("Exiting get_textwebField method ..."); + return $form_field; + +} + +/** Function to get textfield + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @returns $form_field -- return field:: Type string + */ + +function get_textField($label,$name) +{ + global $log; + $log->debug("Entering get_textField(".$label.",".$name.") method ..."); + $form_field=''; + if($name == "amount") + { + $form_field .=''; + $form_field .= $label.':(U.S Dollar:$)
'; + $form_field .=''; + $log->debug("Exiting get_textField method ..."); + return $form_field; + } + else + { + + $form_field .=''; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textField method ..."); + return $form_field; + } + +} + +/** Function to get account textfield + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @param $tid -- tabid :: Type integer + * @returns $form_field -- return field:: Type string + */ + +function get_textaccField($label,$name,$tid) +{ + global $log; + $log->debug("Entering get_textaccField(".$label.",".$name.",".$tid.") method ..."); + + global $app_strings; + + $form_field=''; + if($tid == 2) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .='
'; + $form_field .=' '; + $log->debug("Exiting get_textaccField method ..."); + return $form_field; + } + else + { + $form_field .=''; + $form_field .= $label.':
'; + $form_field .='
'; + $form_field .=' '; + $log->debug("Exiting get_textaccField method ..."); + return $form_field; + } + +} + +/** Function to get combo field values + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @returns $form_field -- return field:: Type string + */ + +function get_textcomboField($label,$name) +{ + global $log; + $log->debug("Entering get_textcomboField(".$label.",".$name.") method ..."); + $form_field=''; + if($name == "sales_stage") + { + $comboFieldNames = Array('leadsource'=>'leadsource_dom' + ,'opportunity_type'=>'opportunity_type_dom' + ,'sales_stage'=>'sales_stage_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + } + if($name == "productcategory") + { + $comboFieldNames = Array('productcategory'=>'productcategory_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + } + if($name == "ticketpriorities") + { + $comboFieldNames = Array('ticketpriorities'=>'ticketpriorities_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.':
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + } + if($name == "activitytype") + { + $comboFieldNames = Array('activitytype'=>'activitytype_dom', + 'duration_minutes'=>'duration_minutes_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.'
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + + } + if($name == "eventstatus") + { + $comboFieldNames = Array('eventstatus'=>'eventstatus_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.'
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + + + } + if($name == "taskstatus") + { + $comboFieldNames = Array('taskstatus'=>'taskstatus_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + $form_field .=''; + $form_field .= $label.'
'; + $form_field .=''; + $log->debug("Exiting get_textcomboField method ..."); + return $form_field; + } + + + +} + +/** Function to get date field + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @param $tid -- tabid :: Type integer + * @returns $form_field -- return field:: Type string + */ + + +function get_textdateField($label,$name,$tid) +{ + global $log; + $log->debug("Entering get_textdateField(".$label.",".$name.",".$tid.") method ..."); + global $theme; + global $app_strings; + global $current_user; + + $ntc_date_format = $app_strings['NTC_DATE_FORMAT']; + $ntc_time_format = $app_strings['NTC_TIME_FORMAT']; + + $form_field=''; + $default_date_start = date('Y-m-d'); + $default_time_start = date('H:i'); + $dis_value=getNewDisplayDate(); + + if($tid == 2) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .='('.$current_user->date_format.')
'; + $form_field .=' '; + $form_field .=''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + + } + if($tid == 9) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=' '; + $form_field.= ' '; + $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + } + if($tid == 16) + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=' '; + $form_field.= ' '; + $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + } + + else + { + $form_field .=''; + $form_field .= '*'; + $form_field .= $label.':
'; + $form_field .=' '; + $form_field.= ' '; + $form_field.='
('.$current_user->date_format.') '.$ntc_time_format.''; + $log->debug("Exiting get_textdateField method ..."); + return $form_field; + } + +} + +/** Function to get duration text field in activity + * @param $label -- field label :: Type string + * @param $name -- field name :: Type string + * @param $tid -- tabid :: Type integer + * @returns $form_field -- return field:: Type string + */ + +function get_textdurationField($label,$name,$tid) +{ + global $log; + $log->debug("Entering get_textdurationField(".$label.",".$name.",".$tid.") method ..."); + $form_field=''; + if($tid == 16) + { + + $comboFieldNames = Array('activitytype'=>'activitytype_dom', + 'duration_minutes'=>'duration_minutes_dom'); + $comboFieldArray = getComboArray($comboFieldNames); + + $form_field .=''; + $form_field .= $label.'
'; + $form_field .=' '; + $form_field .='
(hours/minutes)
'; + $log->debug("Exiting get_textdurationField method ..."); + return $form_field; + } +} + +/** Function to get email text field + * @param $module -- module name :: Type name + * @param $id -- entity id :: Type integer + * @returns $hidden -- hidden:: Type string + */ + +//Added to get the parents list as hidden for Emails -- 09-11-2005 +function getEmailParentsList($module,$id,$focus = false) +{ + global $log; + $log->debug("Entering getEmailParentsList(".$module.",".$id.") method ..."); + global $adb; + // If the information is not sent then read it + if($focus === false) { + if($module == 'Contacts') + $focus = new Contacts(); + if($module == 'Leads') + $focus = new Leads(); + + $focus->retrieve_entity_info($id,$module); + } + + $fieldid = 0; + $fieldname = 'email'; + if($focus->column_fields['email'] == '' && $focus->column_fields['yahooid'] != '' ) + $fieldname = 'yahooid'; + elseif($focus->column_fields['email'] == '' && $focus->column_fields['secondaryemail'] != '' ) + $fieldname='secondaryemail'; + $res = $adb->pquery("select * from vtiger_field where tabid = ? and fieldname= ? and vtiger_field.presence in (0,2)", array(getTabid($module), $fieldname)); + $fieldid = $adb->query_result($res,0,'fieldid'); + + $hidden .= ''; + $hidden .= ''; + + $log->debug("Exiting getEmailParentsList method ..."); + return $hidden; +} + +/** This Function returns the current status of the specified Purchase Order. + * The following is the input parameter for the function + * $po_id --> Purchase Order Id, Type:Integer + */ +function getPoStatus($po_id) +{ + global $log; + $log->debug("Entering getPoStatus(".$po_id.") method ..."); + + global $log; + $log->info("in getPoName ".$po_id); + + global $adb; + $sql = "select postatus from vtiger_purchaseorder where purchaseorderid=?"; + $result = $adb->pquery($sql, array($po_id)); + $po_status = $adb->query_result($result,0,"postatus"); + $log->debug("Exiting getPoStatus method ..."); + return $po_status; +} + +/** This Function adds the specified product quantity to the Product Quantity in Stock in the Warehouse + * The following is the input parameter for the function: + * $productId --> ProductId, Type:Integer + * $qty --> Quantity to be added, Type:Integer + */ +function addToProductStock($productId,$qty) +{ + global $log; + $log->debug("Entering addToProductStock(".$productId.",".$qty.") method ..."); + global $adb; + $qtyInStck=getProductQtyInStock($productId); + $updQty=$qtyInStck + $qty; + $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?"; + $adb->pquery($sql, array($updQty, $productId)); + $log->debug("Exiting addToProductStock method ..."); + +} + +/** This Function adds the specified product quantity to the Product Quantity in Demand in the Warehouse + * @param int $productId - ProductId + * @param int $qty - Quantity to be added + */ +function addToProductDemand($productId,$qty) +{ + global $log; + $log->debug("Entering addToProductDemand(".$productId.",".$qty.") method ..."); + global $adb; + $qtyInStck=getProductQtyInDemand($productId); + $updQty=$qtyInStck + $qty; + $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?"; + $adb->pquery($sql, array($updQty, $productId)); + $log->debug("Exiting addToProductDemand method ..."); + +} + +/** This Function subtract the specified product quantity to the Product Quantity in Stock in the Warehouse + * @param int $productId - ProductId + * @param int $qty - Quantity to be subtracted + */ +function deductFromProductStock($productId,$qty) +{ + global $log; + $log->debug("Entering deductFromProductStock(".$productId.",".$qty.") method ..."); + global $adb; + $qtyInStck=getProductQtyInStock($productId); + $updQty=$qtyInStck - $qty; + $sql = "UPDATE vtiger_products set qtyinstock=? where productid=?"; + $adb->pquery($sql, array($updQty, $productId)); + $log->debug("Exiting deductFromProductStock method ..."); + +} + +/** This Function subtract the specified product quantity to the Product Quantity in Demand in the Warehouse + * @param int $productId - ProductId + * @param int $qty - Quantity to be subtract + */ +function deductFromProductDemand($productId,$qty) +{ + global $log; + $log->debug("Entering deductFromProductDemand(".$productId.",".$qty.") method ..."); + global $adb; + $qtyInStck=getProductQtyInDemand($productId); + $updQty=$qtyInStck - $qty; + $sql = "UPDATE vtiger_products set qtyindemand=? where productid=?"; + $adb->pquery($sql, array($updQty, $productId)); + $log->debug("Exiting deductFromProductDemand method ..."); + +} + + +/** This Function returns the current product quantity in stock. + * The following is the input parameter for the function: + * $product_id --> ProductId, Type:Integer + */ +function getProductQtyInStock($product_id) +{ + global $log; + $log->debug("Entering getProductQtyInStock(".$product_id.") method ..."); + global $adb; + $query1 = "select qtyinstock from vtiger_products where productid=?"; + $result=$adb->pquery($query1, array($product_id)); + $qtyinstck= $adb->query_result($result,0,"qtyinstock"); + $log->debug("Exiting getProductQtyInStock method ..."); + return $qtyinstck; + + +} + +/** This Function returns the current product quantity in demand. + * @param int $product_id - ProductId + * @return int $qtyInDemand - Quantity in Demand of a product + */ +function getProductQtyInDemand($product_id) +{ + global $log; + $log->debug("Entering getProductQtyInDemand(".$product_id.") method ..."); + global $adb; + $query1 = "select qtyindemand from vtiger_products where productid=?"; + $result = $adb->pquery($query1, array($product_id)); + $qtyInDemand = $adb->query_result($result,0,"qtyindemand"); + $log->debug("Exiting getProductQtyInDemand method ..."); + return $qtyInDemand; +} + +/** Function to seperate the Date and Time + * This function accepts a sting with date and time and + * returns an array of two elements.The first element + * contains the date and the second one contains the time + */ +function getDateFromDateAndtime($date_time) +{ + global $log; + $log->debug("Entering getDateFromDateAndtime(".$date_time.") method ..."); + $result = explode(" ",$date_time); + $log->debug("Exiting getDateFromDateAndtime method ..."); + return $result; +} + + +/** Function to get header for block in edit/create and detailview + * @param $header_label -- header label :: Type string + * @returns $output -- output:: Type string + */ + +function getBlockTableHeader($header_label) +{ + global $log; + $log->debug("Entering getBlockTableHeader(".$header_label.") method ..."); + global $mod_strings; + $label = $mod_strings[$header_label]; + $output = $label; + $log->debug("Exiting getBlockTableHeader method ..."); + return $output; + +} + + + +/** Function to get the vtiger_table name from 'field' vtiger_table for the input vtiger_field based on the module + * @param : string $module - current module value + * @param : string $fieldname - vtiger_fieldname to which we want the vtiger_tablename + * @return : string $tablename - vtiger_tablename in which $fieldname is a column, which is retrieved from 'field' vtiger_table per $module basis + */ +function getTableNameForField($module,$fieldname) +{ + global $log; + $log->debug("Entering getTableNameForField(".$module.",".$fieldname.") method ..."); + global $adb; + $tabid = getTabid($module); + //Asha + if($module == 'Calendar') { + $tabid = array('9','16'); + } + $sql = "select tablename from vtiger_field where tabid in (". generateQuestionMarks($tabid) .") and vtiger_field.presence in (0,2) and columnname like ?"; + $res = $adb->pquery($sql, array($tabid, '%'.$fieldname.'%')); + + $tablename = ''; + if($adb->num_rows($res) > 0) + { + $tablename = $adb->query_result($res,0,'tablename'); + } + + $log->debug("Exiting getTableNameForField method ..."); + return $tablename; +} + +/** Function to get parent record owner + * @param $tabid -- tabid :: Type integer + * @param $parModId -- parent module id :: Type integer + * @param $record_id -- record id :: Type integer + * @returns $parentRecOwner -- parentRecOwner:: Type integer + */ + +function getParentRecordOwner($tabid,$parModId,$record_id) +{ + global $log; + $log->debug("Entering getParentRecordOwner(".$tabid.",".$parModId.",".$record_id.") method ..."); + $parentRecOwner=Array(); + $parentTabName=getTabname($parModId); + $relTabName=getTabname($tabid); + $fn_name="get".$relTabName."Related".$parentTabName; + $ent_id=$fn_name($record_id); + if($ent_id != '') + { + $parentRecOwner=getRecordOwnerId($ent_id); + } + $log->debug("Exiting getParentRecordOwner method ..."); + return $parentRecOwner; +} + +/** Function to get potential related accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getPotentialsRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getPotentialsRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select related_to from vtiger_potential where potentialid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'related_to'); + $log->debug("Exiting getPotentialsRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get email related accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ +function getEmailsRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getEmailsRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Accounts' and activityid=?"; + $result = $adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'crmid'); + $log->debug("Exiting getEmailsRelatedAccounts method ..."); + return $accountid; +} +/** Function to get email related Leads + * @param $record_id -- record id :: Type integer + * @returns $leadid -- leadid:: Type integer + */ + +function getEmailsRelatedLeads($record_id) +{ + global $log; + $log->debug("Entering getEmailsRelatedLeads(".$record_id.") method ..."); + global $adb; + $query = "select vtiger_seactivityrel.crmid from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid where vtiger_crmentity.setype='Leads' and activityid=?"; + $result = $adb->pquery($query, array($record_id)); + $leadid=$adb->query_result($result,0,'crmid'); + $log->debug("Exiting getEmailsRelatedLeads method ..."); + return $leadid; +} + +/** Function to get HelpDesk related Accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getHelpDeskRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getHelpDeskRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select parent_id from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.parent_id where ticketid=? and vtiger_crmentity.setype='Accounts'"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'parent_id'); + $log->debug("Exiting getHelpDeskRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get Quotes related Accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getQuotesRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getQuotesRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select accountid from vtiger_quotes where quoteid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'accountid'); + $log->debug("Exiting getQuotesRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get Quotes related Potentials + * @param $record_id -- record id :: Type integer + * @returns $potid -- potid:: Type integer + */ + +function getQuotesRelatedPotentials($record_id) +{ + global $log; + $log->debug("Entering getQuotesRelatedPotentials(".$record_id.") method ..."); + global $adb; + $query="select potentialid from vtiger_quotes where quoteid=?"; + $result=$adb->pquery($query, array($record_id)); + $potid=$adb->query_result($result,0,'potentialid'); + $log->debug("Exiting getQuotesRelatedPotentials method ..."); + return $potid; +} + +/** Function to get Quotes related Potentials + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getSalesOrderRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getSalesOrderRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select accountid from vtiger_salesorder where salesorderid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'accountid'); + $log->debug("Exiting getSalesOrderRelatedAccounts method ..."); + return $accountid; +} + +/** Function to get SalesOrder related Potentials + * @param $record_id -- record id :: Type integer + * @returns $potid -- potid:: Type integer + */ + +function getSalesOrderRelatedPotentials($record_id) +{ + global $log; + $log->debug("Entering getSalesOrderRelatedPotentials(".$record_id.") method ..."); + global $adb; + $query="select potentialid from vtiger_salesorder where salesorderid=?"; + $result=$adb->pquery($query, array($record_id)); + $potid=$adb->query_result($result,0,'potentialid'); + $log->debug("Exiting getSalesOrderRelatedPotentials method ..."); + return $potid; +} +/** Function to get SalesOrder related Quotes + * @param $record_id -- record id :: Type integer + * @returns $qtid -- qtid:: Type integer + */ + +function getSalesOrderRelatedQuotes($record_id) +{ + global $log; + $log->debug("Entering getSalesOrderRelatedQuotes(".$record_id.") method ..."); + global $adb; + $query="select quoteid from vtiger_salesorder where salesorderid=?"; + $result=$adb->pquery($query, array($record_id)); + $qtid=$adb->query_result($result,0,'quoteid'); + $log->debug("Exiting getSalesOrderRelatedQuotes method ..."); + return $qtid; +} + +/** Function to get Invoice related Accounts + * @param $record_id -- record id :: Type integer + * @returns $accountid -- accountid:: Type integer + */ + +function getInvoiceRelatedAccounts($record_id) +{ + global $log; + $log->debug("Entering getInvoiceRelatedAccounts(".$record_id.") method ..."); + global $adb; + $query="select accountid from vtiger_invoice where invoiceid=?"; + $result=$adb->pquery($query, array($record_id)); + $accountid=$adb->query_result($result,0,'accountid'); + $log->debug("Exiting getInvoiceRelatedAccounts method ..."); + return $accountid; +} +/** Function to get Invoice related SalesOrder + * @param $record_id -- record id :: Type integer + * @returns $soid -- soid:: Type integer + */ + +function getInvoiceRelatedSalesOrder($record_id) +{ + global $log; + $log->debug("Entering getInvoiceRelatedSalesOrder(".$record_id.") method ..."); + global $adb; + $query="select salesorderid from vtiger_invoice where invoiceid=?"; + $result=$adb->pquery($query, array($record_id)); + $soid=$adb->query_result($result,0,'salesorderid'); + $log->debug("Exiting getInvoiceRelatedSalesOrder method ..."); + return $soid; +} + + +/** Function to get Days and Dates in between the dates specified + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_days_n_dates($st,$en) +{ + global $log; + $log->debug("Entering get_days_n_dates(".$st.",".$en.") method ..."); + $stdate_arr=explode("-",$st); + $endate_arr=explode("-",$en); + + $dateDiff = mktime(0,0,0,$endate_arr[1],$endate_arr[2],$endate_arr[0]) - mktime(0,0,0,$stdate_arr[1],$stdate_arr[2],$stdate_arr[0]);//to get dates difference + + $days = floor($dateDiff/60/60/24)+1; //to calculate no of. days + for($i=0;$i<$days;$i++) + { + $day_date[] = date("Y-m-d",mktime(0,0,0,date("$stdate_arr[1]"),(date("$stdate_arr[2]")+($i)),date("$stdate_arr[0]"))); + } + if(!isset($day_date)) + $day_date=0; + $nodays_dates=array($days,$day_date); + $log->debug("Exiting get_days_n_dates method ..."); + return $nodays_dates; //passing no of days , days in between the days +}//function end + + +/** Function to get the start and End Dates based upon the period which we give + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function start_end_dates($period) +{ + global $log; + $log->debug("Entering start_end_dates(".$period.") method ..."); + $st_thisweek= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y"))); + if($period=="tweek") + { + $st_date= date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-date("w")),date("Y"))); + $end_date = date("Y-m-d",mktime(0,0,0,date("n"),(date("j")-1),date("Y"))); + $st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y"))); + if($st_week==0) + { + $start_week=explode("-",$st_thisweek); + $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]"))); + $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]"))); + } + $period_type="week"; + $width="360"; + } + else if($period=="lweek") + { + $start_week=explode("-",$st_thisweek); + $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-7),date("$start_week[0]"))); + $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-1),date("$start_week[0]"))); + $st_week= date("w",mktime(0,0,0,date("n"),date("j"),date("Y"))); + if($st_week==0) + { + $start_week=explode("-",$st_thisweek); + $st_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-14),date("$start_week[0]"))); + $end_date = date("Y-m-d",mktime(0,0,0,date("$start_week[1]"),(date("$start_week[2]")-8),date("$start_week[0]"))); + } + $period_type="week"; + $width="360"; + } + else if($period=="tmon") + { + $period_type="month"; + $width="840"; + $st_date = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y"))); + $end_date = date("Y-m-t"); + + } + else if($period=="lmon") + { + $st_date=date("Y-m-d",mktime(0,0,0,date("n")-1,date("1"),date("Y"))); + $end_date = date("Y-m-d",mktime(0, 0, 1, date("n"), 0,date("Y"))); + $period_type="month"; + $start_month=date("d",mktime(0,0,0,date("n"),date("j"),date("Y"))); + if($start_month==1) + { + $st_date=date("Y-m-d",mktime(0,0,0,date("n")-2,date("1"),date("Y"))); + $end_date = date("Y-m-d",mktime(0, 0, 1, date("n")-1, 0,date("Y"))); + } + + $width="840"; + } + else + { + $curr_date=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y"))); + $today_date=explode("-",$curr_date); + $lastday_date=date("Y-m-d",mktime(0,0,0,date("$today_date[1]"),date("$today_date[2]")-1,date("$today_date[0]"))); + $st_date=$lastday_date; + $end_date=$lastday_date; + $period_type="yday"; + $width="250"; + } + if($period_type=="yday") + $height="160"; + else + $height="250"; + $datevalues=array($st_date,$end_date,$period_type,$width,$height); + $log->debug("Exiting start_end_dates method ..."); + return $datevalues; +}//function ends + + +/** Function to get the Graph and vtiger_table format for a particular date + based upon the period + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function Graph_n_table_format($period_type,$date_value) +{ + global $log; + $log->debug("Entering Graph_n_table_format(".$period_type.",".$date_value.") method ..."); + $date_val=explode("-",$date_value); + if($period_type=="month") //to get the vtiger_table format dates + { + $table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); + $graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); + } + else if($period_type=="week") + { + $table_format=date("d/m",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); + $graph_format=date("D",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); + } + else if($period_type=="yday") + { + $table_format=date("j",mktime(0,0,0,date($date_val[1]),(date($date_val[2])),date($date_val[0]))); + $graph_format=$table_format; + } + $values=array($graph_format,$table_format); + $log->debug("Exiting Graph_n_table_format method ..."); + return $values; +} + +/** Function to get image count for a given product + * @param $id -- product id :: Type integer + * @returns count -- count:: Type integer + */ + +function getImageCount($id) +{ + global $log; + $log->debug("Entering getImageCount(".$id.") method ..."); + global $adb; + $image_lists=array(); + $query="select imagename from vtiger_products where productid=?"; + $result=$adb->pquery($query, array($id)); + $imagename=$adb->query_result($result,0,'imagename'); + $image_lists=explode("###",$imagename); + $log->debug("Exiting getImageCount method ..."); + return count($image_lists); + +} + +/** Function to get user image for a given user + * @param $id -- user id :: Type integer + * @returns $image_name -- image name:: Type string + */ + +function getUserImageName($id) +{ + global $log; + $log->debug("Entering getUserImageName(".$id.") method ..."); + global $adb; + $query = "select imagename from vtiger_users where id=?"; + $result = $adb->pquery($query, array($id)); + $image_name = $adb->query_result($result,0,"imagename"); + $log->debug("Inside getUserImageName. The image_name is ".$image_name); + $log->debug("Exiting getUserImageName method ..."); + return $image_name; + +} + +/** Function to get all user images for displaying it in listview + * @returns $image_name -- image name:: Type array + */ + +function getUserImageNames() +{ + global $log; + $log->debug("Entering getUserImageNames() method ..."); + global $adb; + $query = "select imagename from vtiger_users where deleted=0"; + $result = $adb->pquery($query, array()); + $image_name=array(); + for($i=0;$i<$adb->num_rows($result);$i++) + { + if($adb->query_result($result,$i,"imagename")!='') + $image_name[] = $adb->query_result($result,$i,"imagename"); + } + $log->debug("Inside getUserImageNames."); + if(count($image_name) > 0) + { + $log->debug("Exiting getUserImageNames method ..."); + return $image_name; + } +} + +/** Function to remove the script tag in the contents + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function strip_selected_tags($text, $tags = array()) +{ + $args = func_get_args(); + $text = array_shift($args); + $tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags; + foreach ($tags as $tag){ + if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){ + $text = str_replace($found[0],$found[1],$text); + } + } + + return $text; +} + +/** Function to check whether user has opted for internal mailer + * @returns $int_mailer -- int mailer:: Type boolean + */ +function useInternalMailer() { + global $current_user,$adb; + return $adb->query_result($adb->pquery("select int_mailer from vtiger_mail_accounts where user_id=?", array($current_user->id)),0,"int_mailer"); +} + +/** +* the function is like unescape in javascript +* added by dingjianting on 2006-10-1 for picklist editor +*/ +function utf8RawUrlDecode ($source) { + global $default_charset; + $decodedStr = ""; + $pos = 0; + $len = strlen ($source); + while ($pos < $len) { + $charAt = substr ($source, $pos, 1); + if ($charAt == '%') { + $pos++; + $charAt = substr ($source, $pos, 1); + if ($charAt == 'u') { + // we got a unicode character + $pos++; + $unicodeHexVal = substr ($source, $pos, 4); + $unicode = hexdec ($unicodeHexVal); + $entity = "&#". $unicode . ';'; + $decodedStr .= utf8_encode ($entity); + $pos += 4; + } + else { + // we have an escaped ascii character + $hexVal = substr ($source, $pos, 2); + $decodedStr .= chr (hexdec ($hexVal)); + $pos += 2; + } + } else { + $decodedStr .= $charAt; + $pos++; + } + } + if(strtolower($default_charset) == 'utf-8') + return html_to_utf8($decodedStr); + else + return $decodedStr; + //return html_to_utf8($decodedStr); +} + +/** +*simple HTML to UTF-8 conversion: +*/ +function html_to_utf8 ($data) +{ + return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data); +} + +function _html_to_utf8 ($data) +{ + if ($data > 127) + { + $i = 5; + while (($i--) > 0) + { + if ($data != ($a = $data % ($p = pow(64, $i)))) + { + $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p)); + for ($i; $i > 0; $i--) + $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p)); + break; + } + } + } + else + $ret = "&#$data;"; + return $ret; +} + +// Return Question mark +function _questionify($v){ + return "?"; +} + +/** +* Function to generate question marks for a given list of items +*/ +function generateQuestionMarks($items_list) { + // array_map will call the function specified in the first parameter for every element of the list in second parameter + if (is_array($items_list)) { + return implode(",", array_map("_questionify", $items_list)); + } else { + return implode(",", array_map("_questionify", explode(",", $items_list))); + } +} + +/** +* Function to find the UI type of a field based on the uitype id +*/ +function is_uitype($uitype, $reqtype) { + $ui_type_arr = array( + '_date_' => array(5, 6, 23, 70), + '_picklist_' => array(15, 16, 52, 53, 54, 55, 59, 62, 63, 66, 68, 76, 77, 78, 80, 98, 101, 115, 357), + '_users_list_' => array(52), + ); + + if ($ui_type_arr[$reqtype] != null) { + if (in_array($uitype, $ui_type_arr[$reqtype])) { + return true; + } + } + return false; +} +/** + * Function to escape quotes + * @param $value - String in which single quotes have to be replaced. + * @return Input string with single quotes escaped. + */ +function escape_single_quotes($value) { + if (isset($value)) $value = str_replace("'", "\'", $value); + return $value; +} + +/** + * Function to format the input value for SQL like clause. + * @param $str - Input string value to be formatted. + * @param $flag - By default set to 0 (Will look for cases %string%). + * If set to 1 - Will look for cases %string. + * If set to 2 - Will look for cases string%. + * @return String formatted as per the SQL like clause requirement + */ +function formatForSqlLike($str, $flag=0,$is_field=false) { + global $adb; + if (isset($str)) { + if($is_field==false){ + $str = str_replace('%', '\%', $str); + $str = str_replace('_', '\_', $str); + if ($flag == 0) { + $str = '%'. $str .'%'; + } elseif ($flag == 1) { + $str = '%'. $str; + } elseif ($flag == 2) { + $str = $str .'%'; + } + } else { + if ($flag == 0) { + $str = 'concat("%",'. $str .',"%")'; + } elseif ($flag == 1) { + $str = 'concat("%",'. $str .')'; + } elseif ($flag == 2) { + $str = 'concat('. $str .',"%")'; + } + } + } + return $adb->sql_escape_string($str); +} + +/** + * Get Current Module (global variable or from request) + */ +function getCurrentModule($perform_set=false) { + global $currentModule,$root_directory; + if(isset($currentModule)) return $currentModule; + + // Do some security check and return the module information + if(isset($_REQUEST['module'])) + { + $is_module = false; + $module = $_REQUEST['module']; + $dir = @scandir($root_directory."modules"); + $temp_arr = Array("CVS","Attic"); + $res_arr = @array_intersect($dir,$temp_arr); + if(count($res_arr) == 0 && !preg_match("/[\/.]/",$module)) { + if(@in_array($module,$dir)) + $is_module = true; + } + + if($is_module) { + if($perform_set) $currentModule = $module; + return $module; + } + } + return null; +} + + +/** + * Set the language strings. + */ +function setCurrentLanguage($active_module=null) { + global $current_language, $default_language, $app_strings, $app_list_strings, $mod_strings, $currentModule; + + if($active_module==null) { + if (!isset($currentModule)) + $active_module = getCurrentModule(); + else + $active_module = $currentModule; + } + + if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') + { + $current_language = $_SESSION['authenticated_user_language']; + } + else + { + $current_language = $default_language; + } + + //set module and application string arrays based upon selected language + if (!isset($app_strings)) + $app_strings = return_application_language($current_language); + if (!isset($app_list_strings)) + $app_list_strings = return_app_list_strings_language($current_language); + if (!isset($mod_strings) && isset($active_module)) + $mod_strings = return_module_language($current_language, $active_module); +} + +/** Function used to get all the picklists and their values for a module + @param string $module - Module name to which the list of picklists and their values needed + @return array $fieldlists - Array of picklists and their values +**/ +function getAccessPickListValues($module) +{ + global $adb, $log; + global $current_user; + $log->debug("Entering into function getAccessPickListValues($module)"); + + $id = getTabid($module); + $query = "select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from vtiger_field where tabid = ? and uitype in ('15','33','55') and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($query, array($id)); + + $roleid = $current_user->roleid; + $subrole = getRoleSubordinates($roleid); + + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + + $temp_status = Array(); + for($i=0;$i < $adb->num_rows($result);$i++) + { + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $columnname = $adb->query_result($result,$i,"columnname"); + $tabid = $adb->query_result($result,$i,"tabid"); + $uitype = $adb->query_result($result,$i,"uitype"); + + $keyvalue = $columnname; + $fieldvalues = Array(); + if (count($roleids) > 1) + { + $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\") and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; + } + else + { + $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid ='".$roleid."' and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; + } + if($fieldname != 'firstname') + $mulselresult = $adb->query($mulsel); + for($j=0;$j < $adb->num_rows($mulselresult);$j++) + { + $fieldvalues[] = $adb->query_result($mulselresult,$j,$fieldname); + } + $field_count = count($fieldvalues); + if($uitype == 15 && $field_count > 0 && ($fieldname == 'taskstatus' || $fieldname == 'eventstatus')) + { + $temp_count =count($temp_status[$keyvalue]); + if($temp_count > 0) + { + for($t=0;$t < $field_count;$t++) + { + $temp_status[$keyvalue][($temp_count+$t)] = $fieldvalues[$t]; + } + $fieldvalues = $temp_status[$keyvalue]; + } + else + $temp_status[$keyvalue] = $fieldvalues; + } + if($uitype == 33) + $fieldlists[1][$keyvalue] = $fieldvalues; + else if($uitype == 55 && $fieldname == 'salutationtype') + $fieldlists[$keyvalue] = $fieldvalues; + else if($uitype == 15) + $fieldlists[$keyvalue] = $fieldvalues; + } + $log->debug("Exit from function getAccessPickListValues($module)"); + + return $fieldlists; +} + +function get_config_status() { + global $default_charset; + if(strtolower($default_charset) == 'utf-8') + $config_status=1; + else + $config_status=0; + return $config_status; +} + +function getMigrationCharsetFlag() { + global $adb; + + if(!$adb->isPostgres()) + $db_status=check_db_utf8_support($adb); + $config_status=get_config_status(); + + if ($db_status == $config_status) { + if ($db_status == 1) { // Both are UTF-8 + $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_UTF8; + } else { // Both are Non UTF-8 + $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_NONUTF8; + } + } else { + if ($db_status == 1) { // Database charset is UTF-8 and CRM charset is Non UTF-8 + $db_migration_status = MIG_CHARSET_PHP_NONUTF8_DB_UTF8; + } else { // Database charset is Non UTF-8 and CRM charset is UTF-8 + $db_migration_status = MIG_CHARSET_PHP_UTF8_DB_NONUTF8; + } + } + return $db_migration_status; +} + +/** Function to convert a given time string to Minutes */ +function ConvertToMinutes($time_string) +{ + $interval = split(' ', $time_string); + $interval_minutes = intval($interval[0]); + $interval_string = strtolower($interval[1]); + if($interval_string == 'hour' || $interval_string == 'hours') + { + $interval_minutes = $interval_minutes * 60; + } + elseif($interval_string == 'day' || $interval_string == 'days') + { + $interval_minutes = $interval_minutes * 1440; + } + return $interval_minutes; +} + +//added to find duplicates +/** To get the converted record values which have to be display in duplicates merging tpl*/ +function getRecordValues($id_array,$module) { + global $adb,$current_user; + global $app_strings; + $tabid=getTabid($module); + $query="select fieldname,fieldlabel,uitype from vtiger_field where tabid=? and fieldname not in ('createdtime','modifiedtime') and vtiger_field.presence in (0,2) and uitype not in('4')"; + $result=$adb->pquery($query, array($tabid)); + $no_rows=$adb->num_rows($result); + + $focus = new $module(); + if(isset($id_array) && $id_array !='') { + foreach($id_array as $value_pair['disp_value']) { + $focus->id=$value_pair['disp_value']; + $focus->retrieve_entity_info($value_pair['disp_value'],$module); + $field_values[]=$focus->column_fields; + } + } + + $labl_array=array(); + $value_pair = array(); + $c = 0; + for($i=0;$i<$no_rows;$i++) { + $fld_name=$adb->query_result($result,$i,"fieldname"); + $fld_label=$adb->query_result($result,$i,"fieldlabel"); + $ui_type=$adb->query_result($result,$i,"uitype"); + + if(getFieldVisibilityPermission($module,$current_user->id,$fld_name, 'readwrite') == '0') { + $fld_array []= $fld_name; + $record_values[$c][$fld_label] = Array(); + $ui_value[]=$ui_type; + for($j=0;$j < count($field_values);$j++) { + + if($ui_type ==56) { + if($field_values[$j][$fld_name] == 0) + $value_pair['disp_value']=$app_strings['no']; + else + $value_pair['disp_value']=$app_strings['yes']; + } elseif($ui_type == 51 || $ui_type == 50) { + $entity_id=$field_values[$j][$fld_name]; + if($module !='Products') + $entity_name=getAccountName($entity_id); + else + $entity_name=getProductName($entity_id); + $value_pair['disp_value']=$entity_name; + } elseif($ui_type == 53) { + $owner_id=$field_values[$j][$fld_name]; + $ownername=getOwnerName($owner_id); + $value_pair['disp_value']=$ownername; + } elseif($ui_type ==57) { + $contact_id= $field_values[$j][$fld_name]; + if($contact_id != '') { + $displayValueArray = getEntityName('Contacts', $contact_id); + if (!empty($displayValueArray)) { + foreach ($displayValueArray as $key => $field_value) { + $contactname = $field_value; + } + } + } + $value_pair['disp_value']=$contactname; + } elseif($ui_type == 75 || $ui_type ==81) { + $vendor_id=$field_values[$j][$fld_name]; + if($vendor_id != '') { + $vendor_name=getVendorName($vendor_id); + } + $value_pair['disp_value']=$vendor_name; + } elseif($ui_type == 52) { + $user_id = $field_values[$j][$fld_name]; + $user_name=getUserFullName($user_id); + $value_pair['disp_value']=$user_name; + } elseif($ui_type ==68) { + $parent_id = $field_values[$j][$fld_name]; + $value_pair['disp_value'] = getAccountName($parent_id); + if($value_pair['disp_value'] == '' || $value_pair['disp_value'] == NULL) { + $displayValueArray = getEntityName('Contacts', $parent_id); + if (!empty($displayValueArray)) { + foreach ($displayValueArray as $key => $field_value) { + $contact_name = $field_value; + } + } else { + $contact_name=''; + } + $value_pair['disp_value'] = $contact_name; + } + } elseif($ui_type ==59) { + $product_name=getProductName($field_values[$j][$fld_name]); + if($product_name != '') + $value_pair['disp_value']=$product_name; + else $value_pair['disp_value']=''; + } elseif($ui_type==58) { + $campaign_name=getCampaignName($field_values[$j][$fld_name]); + if($campaign_name != '') + $value_pair['disp_value']=$campaign_name; + else $value_pair['disp_value']=''; + } elseif($ui_type == 10) { + $value_pair['disp_value'] = getRecordInfoFromID($field_values[$j][$fld_name]); + }elseif($ui_type == 5 || $ui_type == 6 || $ui_type == 23){ + if ($field_values[$j][$fld_name] != '' && $field_values[$j][$fld_name] + != '0000-00-00') { + $date = new DateTimeField($field_values[$j][$fld_name]); + $value_pair['disp_value'] = $date->getDisplayDate(); + if(strpos($field_values[$j][$fld_name], ' ') > -1) { + $value_pair['disp_value'] .= (' ' . $date->getDisplayTime()); + } + } elseif ($field_values[$j][$fld_name] == '0000-00-00') { + $value_pair['disp_value'] = ''; + } else { + $value_pair['disp_value'] = $field_values[$j][$fld_name]; + } + }elseif($ui_type == '71' || $ui_type == '72') { + $currencyField = new CurrencyField($field_values[$j][$fld_name]); + if($ui_type == '72') { + $value_pair['disp_value'] = $currencyField->getDisplayValue(null, true); + } else { + $value_pair['disp_value'] = $currencyField->getDisplayValue(); + } + } else { + $value_pair['disp_value']=$field_values[$j][$fld_name]; + } + $value_pair['org_value'] = $field_values[$j][$fld_name]; + + array_push($record_values[$c][$fld_label],$value_pair); + } + $c++; + } + + } + $parent_array[0]=$record_values; + $parent_array[1]=$fld_array; + $parent_array[2]=$fld_array; + return $parent_array; +} + +/** Function to check whether the relationship entries are exist or not on elationship tables */ +function is_related($relation_table,$crm_field,$related_module_id,$crmid) +{ + global $adb; + $check_res = $adb->query("select * from $relation_table where $crm_field=$related_module_id and crmid=$crmid"); + $count = $adb->num_rows($check_res); + if($count > 0) + return true; + else + return false; +} + +/** Function to get a to find duplicates in a particular module*/ +function getDuplicateQuery($module,$field_values,$ui_type_arr) +{ + global $current_user; + $tbl_col_fld = explode(",", $field_values); + $i=0; + foreach($tbl_col_fld as $val) { + list($tbl[$i], $cols[$i], $fields[$i]) = explode(".", $val); + $tbl_cols[$i] = $tbl[$i]. "." . $cols[$i]; + $i++; + } + $table_cols = implode(",",$tbl_cols); + $sec_parameter = getSecParameterforMerge($module); + + if($module == 'Contacts') + { + $nquery = "SELECT vtiger_contactdetails.contactid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid + LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid + LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid + LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (SELECT $table_cols + FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress ON vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + INNER JOIN vtiger_contactsubdetails ON vtiger_contactaddress.contactaddressid = vtiger_contactsubdetails.contactsubscriptionid + LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid + LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_contactdetails.contactid ASC"; + + } + else if($module == 'Accounts') + { + $nquery="SELECT vtiger_account.accountid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_account + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_account.accountid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (SELECT $table_cols + FROM vtiger_account + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + LEFT JOIN vtiger_accountscf ON vtiger_account.accountid=vtiger_accountscf.accountid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_account.accountid ASC"; + } + else if($module == 'Leads') + { + $nquery = "SELECT vtiger_leaddetails.leadid AS recordid, vtiger_users_last_import.deleted,$table_cols + FROM vtiger_leaddetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid + INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid + LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_leaddetails.leadid + INNER JOIN (SELECT $table_cols + FROM vtiger_leaddetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_leaddetails.leadid + INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid + LEFT JOIN vtiger_leadscf ON vtiger_leadscf.leadid=vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter + GROUP BY $table_cols HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 AND vtiger_leaddetails.converted = 0 $sec_parameter ORDER BY $table_cols,vtiger_leaddetails.leadid ASC"; + + } + else if($module == 'Products') + { + $nquery = "SELECT vtiger_products.productid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_products + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_products.productid + LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (SELECT $table_cols + FROM vtiger_products + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid + LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_products.productid ASC"; + } + else if($module == "HelpDesk") + { + $nquery = "SELECT vtiger_troubletickets.ticketid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_troubletickets + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_troubletickets.ticketid + LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_troubletickets.ticketid + LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id + LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid + INNER JOIN (SELECT $table_cols FROM vtiger_troubletickets + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_ticketcf ON vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + LEFT JOIN vtiger_attachments ON vtiger_attachments.attachmentsid=vtiger_crmentity.crmid + LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id + LEFT JOIN vtiger_ticketcomments ON vtiger_ticketcomments.ticketid = vtiger_crmentity.crmid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_contactdetails contd ON contd.contactid = vtiger_troubletickets.parent_id + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_troubletickets.ticketid ASC"; + } + else if($module == "Potentials") + { + $nquery = "SELECT vtiger_potential.potentialid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_potential + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_potential.potentialid + LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_potential.potentialid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + INNER JOIN (SELECT $table_cols + FROM vtiger_potential + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_potential.potentialid + LEFT JOIN vtiger_potentialscf ON vtiger_potentialscf.potentialid = vtiger_potential.potentialid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 $sec_parameter + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 $sec_parameter ORDER BY $table_cols,vtiger_potential.potentialid ASC"; + } + else if($module == "Vendors") + { + $nquery = "SELECT vtiger_vendor.vendorid AS recordid, + vtiger_users_last_import.deleted,".$table_cols." + FROM vtiger_vendor + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_vendor.vendorid + LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid + LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_vendor.vendorid + INNER JOIN (SELECT $table_cols + FROM vtiger_vendor + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_vendor.vendorid + LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid=vtiger_vendor.vendorid + WHERE vtiger_crmentity.deleted=0 + GROUP BY ".$table_cols." HAVING COUNT(*)>1) as temp + ON ".get_on_clause($field_values,$ui_type_arr,$module) ." + WHERE vtiger_crmentity.deleted=0 ORDER BY $table_cols,vtiger_vendor.vendorid ASC"; + } else { + $modObj = CRMEntity::getInstance($module); + if ($modObj != null && method_exists($modObj, 'getDuplicatesQuery')) { + $nquery = $modObj->getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr); + } + } + return $nquery; +} + +/** Function to return the duplicate records data as a formatted array */ +function getDuplicateRecordsArr($module) +{ + global $adb,$app_strings,$list_max_entries_per_page,$theme; + $field_values_array=getFieldValues($module); + $field_values=$field_values_array['fieldnames_list']; + $fld_arr=$field_values_array['fieldnames_array']; + $col_arr=$field_values_array['columnnames_array']; + $fld_labl_arr=$field_values_array['fieldlabels_array']; + $ui_type=$field_values_array['fieldname_uitype']; + + $dup_query = getDuplicateQuery($module,$field_values,$ui_type); + // added for page navigation + $dup_count_query = substr($dup_query, stripos($dup_query,'FROM'),strlen($dup_query)); + $dup_count_query = "SELECT count(*) as count ".$dup_count_query; + $count_res = $adb->query($dup_count_query); + $no_of_rows = $adb->query_result($count_res,0,"count"); + + if($no_of_rows <= $list_max_entries_per_page) + $_SESSION['dup_nav_start'.$module] = 1; + else if(isset($_REQUEST["start"]) && $_REQUEST["start"] != "" && $_SESSION['dup_nav_start'.$module] != $_REQUEST["start"]) + $_SESSION['dup_nav_start'.$module] = ListViewSession::getRequestStartPage(); + $start = ($_SESSION['dup_nav_start'.$module] != "")?$_SESSION['dup_nav_start'.$module]:1; + $navigation_array = getNavigationValues($start, $no_of_rows, $list_max_entries_per_page); + $start_rec = $navigation_array['start']; + $end_rec = $navigation_array['end_val']; + $navigationOutput = getTableHeaderNavigation($navigation_array, "",$module,"FindDuplicate",""); + if ($start_rec == 0) + $limit_start_rec = 0; + else + $limit_start_rec = $start_rec -1; + $dup_query .= " LIMIT $limit_start_rec, $list_max_entries_per_page"; + //ends + + $nresult=$adb->query($dup_query); + $no_rows=$adb->num_rows($nresult); + require_once('modules/Vtiger/layout_utils.php'); + if($no_rows == 0) + { + if ($_REQUEST['action'] == 'FindDuplicateRecords') + { + //echo "

".$app_strings['LBL_NO_DUPLICATE']." ".$app_strings['LBL_GO_BACK'].".
"; + //die; + echo ""; + echo "
"; + echo "
+ + + + + + + + + +
$app_strings[LBL_NO_DUPLICATE]
+ $app_strings[LBL_GO_BACK]
+
"; + echo "
"; + exit(); + } + else + { + echo "

".$app_strings['LBL_NO_DUPLICATE']."
"; + die; + } + } + + $rec_cnt = 0; + $temp = Array(); + $sl_arr = Array(); + $grp = "group0"; + $gcnt = 0; + $ii = 0; //ii'th record in group + while ( $rec_cnt < $no_rows ) + { + $result = $adb->fetchByAssoc($nresult); + //echo '
';print_r($result);echo '
'; + if($rec_cnt != 0) + { + $sl_arr = array_slice($result,2); + array_walk($temp,'lower_array'); + array_walk($sl_arr,'lower_array'); + $arr_diff = array_diff($temp,$sl_arr); + if(count($arr_diff) > 0) + { + $gcnt++; + $temp = $sl_arr; + $ii = 0; + } + $grp = "group".$gcnt; + } + $fld_values[$grp][$ii]['recordid'] = $result['recordid']; + for($k=0;$k $field_value) { + $contactname = $field_value; + } + } + } + + $result[$col_arr[$k]]=$contactname; + } + if($ui_type[$fld_arr[$k]] == 15 || $ui_type[$fld_arr[$k]] == 16) + { + $result[$col_arr[$k]]=getTranslatedString($result[$col_arr[$k]],$module); + } + if($ui_type[$fld_arr[$k]] == 33){ + $fieldvalue = explode(' |##| ',$result[$col_arr[$k]]); + $result[$col_arr[$k]] = array(); + foreach ($fieldvalue as $picklistValue) { + $result[$col_arr[$k]][] = getTranslatedString($picklistValue,$module); + } + $result[$col_arr[$k]] = implode(', ',$result[$col_arr[$k]]); + } + if($ui_type[$fld_arr[$k]] ==68) + { + $parent_id= $result[$col_arr[$k]]; + if($parent_id != '') + { + $parentname=getParentName($parent_id); + } + + $result[$col_arr[$k]]=$parentname; + } + if($ui_type[$fld_arr[$k]] ==53 || $ui_type[$fld_arr[$k]] ==52) + { + if($result[$col_arr[$k]] != '') + { + $owner=getOwnerName($result[$col_arr[$k]]); + } + $result[$col_arr[$k]]=$owner; + } + if($ui_type[$fld_arr[$k]] ==50 or $ui_type[$fld_arr[$k]] ==51) + { + if($module!='Products') { + $entity_name=getAccountName($result[$col_arr[$k]]); + } else { + $entity_name=getProductName($result[$col_arr[$k]]); + } + if($entity_name != '') { + $result[$col_arr[$k]]=$entity_name; + } else { + $result[$col_arr[$k]]=''; + } + } + if($ui_type[$fld_arr[$k]] ==58) + { + $campaign_name=getCampaignName($result[$col_arr[$k]]); + if($campaign_name != '') + $result[$col_arr[$k]]=$campaign_name; + else $result[$col_arr[$k]]=''; + } + if($ui_type[$fld_arr[$k]] == 59) + { + $product_name=getProductName($result[$col_arr[$k]]); + if($product_name != '') + $result[$col_arr[$k]]=$product_name; + else $result[$col_arr[$k]]=''; + } + /*uitype 10 handling*/ + if($ui_type[$fld_arr[$k]] == 10){ + $result[$col_arr[$k]] = getRecordInfoFromID($result[$col_arr[$k]]); + } + if($ui_type[$fld_arr[$k]] == 5 || $ui_type[$fld_arr[$k]] == 6 || $ui_type[$fld_arr[$k]] == 23){ + if ($$result[$col_arr[$k]] != '' && $$result[$col_arr[$k]] != '0000-00-00') { + $date = new DateTimeField($$result[$col_arr[$k]]); + $value = $date->getDisplayDate(); + if(strpos($$result[$col_arr[$k]], ' ') > -1) { + $value .= (' ' . $date->getDisplayTime()); + } + } elseif ($$result[$col_arr[$k]] == '0000-00-00') { + $value = ''; + } else { + $value = $$result[$col_arr[$k]]; + } + $result[$col_arr[$k]] = $value; + } + if($ui_type[$fld_arr[$k]] == 71) { + $result[$col_arr[$k]] = CurrencyField::convertToUserFormat($result[$col_arr[$k]]); + } + if($ui_type[$fld_arr[$k]] == 72) { + $result[$col_arr[$k]] = CurrencyField::convertToUserFormat($result[$col_arr[$k]], null, true); + } + + $fld_values[$grp][$ii][$fld_labl_arr[$k]] = $result[$col_arr[$k]]; + + } + $fld_values[$grp][$ii]['Entity Type'] = $result['deleted']; + $ii++; + $rec_cnt++; + } + + $gro="group"; + for($i=0;$i<$no_rows;$i++) + { + $ii=0; + $dis_group[]=$fld_values[$gro.$i][$ii]; + $count_group[$i]=count($fld_values[$gro.$i]); + $ii++; + $new_group[]=$dis_group[$i]; + } + $fld_nam=$new_group[0]; + $ret_arr[0]=$fld_values; + $ret_arr[1]=$fld_nam; + $ret_arr[2]=$ui_type; + $ret_arr["navigation"]=$navigationOutput; + return $ret_arr; +} + +/** Function to get on clause criteria for sub tables like address tables to construct duplicate check query */ +function get_special_on_clause($field_list) +{ + $field_array = explode(",",$field_list); + $ret_str = ''; + $sel_clause = ''; + $i=1; + $cnt = count($field_array); + $spl_chk = ($_REQUEST['modulename'] != '')?$_REQUEST['modulename']:$_REQUEST['module']; + foreach($field_array as $fld) + { + $sub_arr = explode(".",$fld); + $tbl_name = $sub_arr[0]; + $col_name = $sub_arr[1]; + $fld_name = $sub_arr[2]; + + //need to handle aditional conditions with sub tables for further modules of duplicate check + if($tbl_name == 'vtiger_leadsubdetails' || $tbl_name == 'vtiger_contactsubdetails') + $tbl_alias = "subd"; + else if($tbl_name == 'vtiger_leadaddress' || $tbl_name == 'vtiger_contactaddress') + $tbl_alias = "addr"; + else if($tbl_name == 'vtiger_account' && $spl_chk == 'Contacts') + $tbl_alias = "acc"; + else if($tbl_name == 'vtiger_accountbillads') + $tbl_alias = "badd"; + else if($tbl_name == 'vtiger_accountshipads') + $tbl_alias = "sadd"; + else if($tbl_name == 'vtiger_crmentity') + $tbl_alias = "crm"; + else if($tbl_name == 'vtiger_customerdetails') + $tbl_alias = "custd"; + else if($tbl_name == 'vtiger_contactdetails' && spl_chk == 'HelpDesk') + $tbl_alias = "contd"; + else if(stripos($tbl_name, 'cf') === (strlen($tbl_name) - strlen('cf'))) + $tbl_alias = "tcf"; // Custom Field Table Prefix to use in subqueries + else + $tbl_alias = "t"; + + $sel_clause .= $tbl_alias.".".$col_name.","; + $ret_str .= " $tbl_name.$col_name = $tbl_alias.$col_name"; + if ($cnt != $i) $ret_str .= " and "; + $i++; + } + $ret_arr['on_clause'] = $ret_str; + $ret_arr['sel_clause'] = trim($sel_clause,","); + return $ret_arr; +} + +/** Function to get on clause criteria for duplicate check queries */ +function get_on_clause($field_list,$uitype_arr,$module) +{ + $field_array = explode(",",$field_list); + $ret_str = ''; + $i=1; + foreach($field_array as $fld) + { + $sub_arr = explode(".",$fld); + $tbl_name = $sub_arr[0]; + $col_name = $sub_arr[1]; + $fld_name = $sub_arr[2]; + + $ret_str .= " ifnull($tbl_name.$col_name,'null') = ifnull(temp.$col_name,'null')"; + + if (count($field_array) != $i) $ret_str .= " and "; + $i++; + } + return $ret_str; +} + +/** call back function to change the array values in to lower case */ +function lower_array(&$string){ + $string = strtolower(trim($string)); +} + +/** Function to get recordids for subquery where condition */ +// TODO - Need to check if this method is used anywhere? +function get_subquery_recordids($sub_query) +{ + global $adb; + //need to update this module whenever duplicate check tool added for new modules + $module_id_array = Array("Accounts"=>"accountid","Contacts"=>"contactid","Leads"=>"leadid","Products"=>"productid","HelpDesk"=>"ticketid","Potentials"=>"potentialid","Vendors"=>"vendorid"); + $id = ($module_id_array[$_REQUEST['modulename']] != '')?$module_id_array[$_REQUEST['modulename']]:$module_id_array[$_REQUEST['module']]; + $sub_res = ''; + $sub_result = $adb->query($sub_query); + $row_count = $adb->num_rows($sub_result); + $sub_res = ''; + if($row_count > 0) + { + while($rows = $adb->fetchByAssoc($sub_result)) + { + $sub_res .= $rows[$id].","; + } + $sub_res = trim($sub_res,","); + } + else + $sub_res .= "''"; + return $sub_res; +} + +/** Function to get tablename, columnname, fieldname, fieldlabel and uitypes of fields of merge criteria for a particular module*/ +function getFieldValues($module) +{ + global $adb,$current_user; + + //In future if we want to change a id mapping to name or other string then we can add that elements in this array. + //$fld_table_arr = Array("vtiger_contactdetails.account_id"=>"vtiger_account.accountname"); + //$special_fld_arr = Array("account_id"=>"accountname"); + + $fld_table_arr = Array(); + $special_fld_arr = Array(); + $tabid = getTabid($module); + + $fieldname_query="select fieldname,fieldlabel,uitype,tablename,columnname from vtiger_field where fieldid in + (select fieldid from vtiger_user2mergefields WHERE tabid=? AND userid=? AND visible = ?) and vtiger_field.presence in (0,2)"; + $fieldname_result = $adb->pquery($fieldname_query, array($tabid, $current_user->id, 1)); + + $field_num_rows = $adb->num_rows($fieldname_result); + + $fld_arr = array(); + $col_arr = array(); + for($j=0;$j< $field_num_rows;$j ++) + { + $tablename = $adb->query_result($fieldname_result,$j,'tablename'); + $column_name = $adb->query_result($fieldname_result,$j,'columnname'); + $field_name = $adb->query_result($fieldname_result,$j,'fieldname'); + $field_lbl = $adb->query_result($fieldname_result,$j,'fieldlabel'); + $ui_type = $adb->query_result($fieldname_result,$j,'uitype'); + $table_col = $tablename.".".$column_name; + if(getFieldVisibilityPermission($module,$current_user->id,$field_name) == 0) + { + $fld_name = ($special_fld_arr[$field_name] != '')?$special_fld_arr[$field_name]:$field_name; + + $fld_arr[] = $fld_name; + $col_arr[] = $column_name; + if($fld_table_arr[$table_col] != '') + $table_col = $fld_table_arr[$table_col]; + + $field_values_array['fieldnames_list'][] = $table_col . "." . $fld_name; + $fld_labl_arr[]=$field_lbl; + $uitype[$field_name]=$ui_type; + } + } + $field_values_array['fieldnames_list']=implode(",",$field_values_array['fieldnames_list']); + $field_values=implode(",",$fld_arr); + $field_values_array['fieldnames']=$field_values; + $field_values_array["fieldnames_array"]=$fld_arr; + $field_values_array["columnnames_array"]=$col_arr; + $field_values_array['fieldlabels_array']=$fld_labl_arr; + $field_values_array['fieldname_uitype']=$uitype; + + return $field_values_array; +} + +/** To get security parameter for a particular module -- By Pavani*/ +function getSecParameterforMerge($module) +{ + global $current_user; + $tab_id = getTabid($module); + $sec_parameter=""; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + if($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) + { + if($module == "Vendors") { + $sec_parameter = ""; + } else { + $sec_parameter=getListViewSecurityParameter($module); + if($module == "Accounts") { + $sec_parameter .= " AND (vtiger_crmentity.smownerid IN (".$current_user->id.") + OR vtiger_crmentity.smownerid IN ( + SELECT vtiger_user2role.userid + FROM vtiger_user2role + INNER JOIN vtiger_users + ON vtiger_users.id = vtiger_user2role.userid + INNER JOIN vtiger_role + ON vtiger_role.roleid = vtiger_user2role.roleid + WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%') + OR vtiger_crmentity.smownerid IN ( + SELECT shareduserid + FROM vtiger_tmp_read_user_sharing_per + WHERE userid=".$current_user->id." + AND tabid=".$tab_id.") + OR (vtiger_crmentity.smownerid in (0) + AND ("; + + if(sizeof($current_user_groups) > 0) { + $sec_parameter .= " vtiger_groups.groupname IN ( + SELECT groupname + FROM vtiger_groups + WHERE groupid IN (". implode(",", getCurrentUserGroupList()) .")) + OR "; + } + $sec_parameter .= " vtiger_groups.groupname IN ( + SELECT vtiger_groups.groupname + FROM vtiger_tmp_read_group_sharing_per + INNER JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_tmp_read_group_sharing_per.sharedgroupid + WHERE userid=".$current_user->id." + AND tabid=".$tab_id.")))) "; + } + } + } + return $sec_parameter; +} + +// Update all the data refering to currency $old_cur to $new_cur +function transferCurrency($old_cur, $new_cur) { + + // Transfer User currency to new currency + transferUserCurrency($old_cur, $new_cur); + + // Transfer Product Currency to new currency + transferProductCurrency($old_cur, $new_cur); + + // Transfer PriceBook Currency to new currency + transferPriceBookCurrency($old_cur, $new_cur); +} + +// Function to transfer the users with currency $old_cur to $new_cur as currency +function transferUserCurrency($old_cur, $new_cur) { + global $log, $adb, $current_user; + $log->debug("Entering function transferUserCurrency..."); + + $sql = "update vtiger_users set currency_id=? where currency_id=?"; + $adb->pquery($sql, array($new_cur, $old_cur)); + + $current_user->retrieve_entity_info($current_user->id,"Users"); + $log->debug("Exiting function transferUserCurrency..."); +} + +// Function to transfer the products with currency $old_cur to $new_cur as currency +function transferProductCurrency($old_cur, $new_cur) { + global $log, $adb; + $log->debug("Entering function updateProductCurrency..."); + $prod_res = $adb->pquery("select productid from vtiger_products where currency_id = ?", array($old_cur)); + $numRows = $adb->num_rows($prod_res); + $prod_ids = array(); + for($i=0;$i<$numRows;$i++) { + $prod_ids[] = $adb->query_result($prod_res,$i,'productid'); + } + if(count($prod_ids) > 0) { + $prod_price_list = getPricesForProducts($new_cur,$prod_ids); + + for($i=0;$ipquery($query, $params); + } + } + $log->debug("Exiting function updateProductCurrency..."); +} + +// Function to transfer the pricebooks with currency $old_cur to $new_cur as currency +// and to update the associated products with list price in $new_cur currency +function transferPriceBookCurrency($old_cur, $new_cur) { + global $log, $adb; + $log->debug("Entering function updatePriceBookCurrency..."); + $pb_res = $adb->pquery("select pricebookid from vtiger_pricebook where currency_id = ?", array($old_cur)); + $numRows = $adb->num_rows($pb_res); + $pb_ids = array(); + for($i=0;$i<$numRows;$i++) { + $pb_ids[] = $adb->query_result($pb_res,$i,'pricebookid'); + } + + if(count($pb_ids) > 0) { + require_once('modules/PriceBooks/PriceBooks.php'); + + for($i=0;$iid = $pb_id; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($pb_id, "PriceBooks"); + $focus->column_fields['currency_id'] = $new_cur; + $focus->save("PriceBooks"); + } + } + + $log->debug("Exiting function updatePriceBookCurrency..."); +} + +//functions for asterisk integration start +/** + * this function returns the caller name based on the phone number that is passed to it + * @param $from - the number which is calling + * returns caller information in name(type) format :: for e.g. Mary Smith (Contact) + * if no information is present in database, it returns :: Unknown Caller (Unknown) + */ +function getCallerName($from) { + global $adb; + + //information found + $callerInfo = getCallerInfo($from); + + if($callerInfo != false){ + $callerName = decode_html($callerInfo['name']); + $module = $callerInfo['module']; + $callerModule = " ($module)"; + $callerID = $callerInfo['id']; + + $caller =$caller."$callerName$callerModule"; + + }else{ + $caller = $caller."
+ ".getTranslatedString('LBL_CREATE_LEAD')."
+ ".getTranslatedString('LBL_CREATE_CONTACT')."
+ ".getTranslatedString('LBL_CREATE_ACCOUNT').""; + } + return $caller; +} + +/** + * this function searches for a given number in vtiger and returns the callerInfo in an array format + * currently the search is made across only leads, accounts and contacts modules + * + * @param $number - the number whose information you want + * @return array in format array(name=>callername, module=>module, id=>id); + */ +function getCallerInfo($number){ + global $adb, $log; + if(empty($number)){ + return false; + } + $caller = "Unknown Number (Unknown)"; //declare caller as unknown in beginning + + $params = array(); + $name = array('Contacts', 'Accounts', 'Leads'); + foreach ($name as $module) { + $focus = CRMEntity::getInstance($module); + $query = $focus->buildSearchQueryForFieldTypes(11, $number); + if(empty($query)) return; + + $result = $adb->pquery($query, array()); + if($adb->num_rows($result) > 0 ){ + $callerName = $adb->query_result($result, 0, "name"); + $callerID = $adb->query_result($result,0,'id'); + $data = array("name"=>$callerName, "module"=>$module, "id"=>$callerID); + return $data; + } + } + return false; +} + +/** + * this function returns the tablename and primarykeys for a given module in array format + * @param object $adb - peardatabase type object + * @param string $module - module name for which you want the array + * @return array(tablename1=>primarykey1,.....) + */ +function get_tab_name_index($adb, $module){ + $tabid = getTabid($module); + $sql = "select * from vtiger_tab_name_index where tabid = ?"; + $result = $adb->pquery($sql, array($tabid)); + $count = $adb->num_rows($result); + $data = array(); + + for($i=0; $i<$count; $i++){ + $tablename = $adb->query_result($result, $i, "tablename"); + $primaryKey = $adb->query_result($result, $i, "primarykey"); + $data[$tablename] = $primaryKey; + } + return $data; +} + +/** + * this function returns the value of use_asterisk from the database for the current user + * @param string $id - the id of the current user + */ +function get_use_asterisk($id){ + global $adb; + if(!vtlib_isModuleActive('PBXManager') || isPermitted('PBXManager', 'index') == 'no'){ + return false; + } + $sql = "select * from vtiger_asteriskextensions where userid = ?"; + $result = $adb->pquery($sql, array($id)); + if($adb->num_rows($result)>0){ + $use_asterisk = $adb->query_result($result, 0, "use_asterisk"); + $asterisk_extension = $adb->query_result($result, 0, "asterisk_extension"); + if($use_asterisk == 0 || empty($asterisk_extension)){ + return 'false'; + }else{ + return 'true'; + } + }else{ + return 'false'; + } +} + +/** + * this function adds a record to the callhistory module + * + * @param string $userExtension - the extension of the current user + * @param string $callfrom - the caller number + * @param string $callto - the called number + * @param string $status - the status of the call (outgoing/incoming/missed) + * @param object $adb - the peardatabase object + */ +function addToCallHistory($userExtension, $callfrom, $callto, $status, $adb, $useCallerInfo){ + $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?"; + $result = $adb->pquery($sql,array($userExtension)); + $userID = $adb->query_result($result, 0, "userid"); + if(empty($userID)) { + // we have observed call to extension not configured in Vtiger will returns NULL + return; + } + $crmID = $adb->getUniqueID('vtiger_crmentity'); + $timeOfCall = date('Y-m-d H:i:s'); + + $sql = "insert into vtiger_crmentity values (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $params = array($crmID, $userID, $userID, 0, "PBXManager", "", $timeOfCall, $timeOfCall, NULL, NULL, 0, 1, 0); + $adb->pquery($sql, $params); + + if(empty($callfrom)){ + $callfrom = "Unknown"; + } + if(empty($callto)){ + $callto = "Unknown"; + } + + if($status == 'outgoing'){ + //call is from user to record + $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?"; + $result = $adb->pquery($sql, array($callfrom)); + if($adb->num_rows($result)>0){ + $userid = $adb->query_result($result, 0, "userid"); + $callerName = getUserFullName($userid); + } + + $receiver = $useCallerInfo; + if(empty($receiver)){ + $receiver = "Unknown"; + }else{ + $receiver = "".$receiver['name'].""; + } + }else{ + //call is from record to user + $sql = "select * from vtiger_asteriskextensions where asterisk_extension=?"; + $result = $adb->pquery($sql,array($callto)); + if($adb->num_rows($result)>0){ + $userid = $adb->query_result($result, 0, "userid"); + $receiver = getUserFullName($userid); + } + $callerName = $useCallerInfo; + if(empty($callerName)){ + $callerName = "Unknown $callfrom"; + }else{ + $callerName = "".decode_html($callerName['name']).""; + } + } + + $sql = "insert into vtiger_pbxmanager (pbxmanagerid,callfrom,callto,timeofcall,status)values (?,?,?,?,?)"; + $params = array($crmID, $callerName, $receiver, $timeOfCall, $status); + $adb->pquery($sql, $params); + return $crmID; +} +//functions for asterisk integration end + +//functions for settings page +/** + * this function returns the blocks for the settings page + */ +function getSettingsBlocks(){ + global $adb; + $sql = "select * from vtiger_settings_blocks order by sequence"; + $result = $adb->query($sql); + $count = $adb->num_rows($result); + $blocks = array(); + + if($count>0){ + for($i=0;$i<$count;$i++){ + $blockid = $adb->query_result($result, $i, "blockid"); + $label = $adb->query_result($result, $i, "label"); + $blocks[$blockid] = $label; + } + } + return $blocks; +} + +/** + * this function returns the fields for the settings page + */ +function getSettingsFields(){ + global $adb; + $sql = "select * from vtiger_settings_field where blockid!=? and active=0 order by blockid,sequence"; + $result = $adb->pquery($sql, array(getSettingsBlockId('LBL_MODULE_MANAGER'))); + $count = $adb->num_rows($result); + $fields = array(); + + if($count>0){ + for($i=0;$i<$count;$i++){ + $blockid = $adb->query_result($result, $i, "blockid"); + $iconpath = $adb->query_result($result, $i, "iconpath"); + $description = $adb->query_result($result, $i, "description"); + $linkto = $adb->query_result($result, $i, "linkto"); + $action = getPropertiesFromURL($linkto, "action"); + $module = getPropertiesFromURL($linkto, "module"); + $name = $adb->query_result($result, $i, "name"); + + $fields[$blockid][] = array("icon"=>$iconpath, "description"=>$description, "link"=>$linkto, "name"=>$name, "action"=>$action, "module"=>$module); + } + + //add blanks for 4-column layout + foreach($fields as $blockid=>&$field){ + if(count($field)>0 && count($field)<4){ + for($i=count($field);$i<4;$i++){ + $field[$i] = array(); + } + } + } + } + return $fields; +} + +/** + * this function takes an url and returns the module name from it + */ +function getPropertiesFromURL($url, $action){ + $result = array(); + preg_match("/$action=([^&]+)/",$url,$result); + return $result[1]; +} + +//functions for settings page end + +/* Function to get the name of the Field which is used for Module Specific Sequence Numbering, if any + * @param module String - Module label + * return Array - Field name and label are returned */ +function getModuleSequenceField($module) { + global $adb, $log; + $log->debug("Entering function getModuleSequenceFieldName ($module)..."); + $field = null; + + if (!empty($module)) { + + // First look at the cached information + $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module); + + if($cachedModuleFields === false) { + //uitype 4 points to Module Numbering Field + $seqColRes = $adb->pquery("SELECT fieldname, fieldlabel, columnname FROM vtiger_field WHERE uitype=? AND tabid=? and vtiger_field.presence in (0,2)", array('4', getTabid($module))); + if($adb->num_rows($seqColRes) > 0) { + $fieldname = $adb->query_result($seqColRes,0,'fieldname'); + $columnname = $adb->query_result($seqColRes,0,'columnname'); + $fieldlabel = $adb->query_result($seqColRes,0,'fieldlabel'); + + $field = array(); + $field['name'] = $fieldname; + $field['column'] = $columnname; + $field['label'] = $fieldlabel; + } + } else { + + foreach($cachedModuleFields as $fieldinfo) { + if($fieldinfo['uitype'] == '4') { + $field = array(); + + $field['name'] = $fieldinfo['fieldname']; + $field['column'] = $fieldinfo['columnname']; + $field['label'] = $fieldinfo['fieldlabel']; + + break; + } + } + } + } + + $log->debug("Exiting getModuleSequenceFieldName..."); + return $field; +} + +/* Function to get the Result of all the field ids allowed for Duplicates merging for specified tab/module (tabid) */ +function getFieldsResultForMerge($tabid) { + global $log, $adb; + $log->debug("Entering getFieldsResultForMerge(".$tabid.") method ..."); + + $nonmergable_tabids = array(29); + + if (in_array($tabid, $nonmergable_tabids)) { + return null; + } + + // List of Fields not allowed for Duplicates Merging based on the module (tabid) [tabid to fields mapping] + $nonmergable_field_tab = Array( + 4 => array('portal','imagename'), + 13 => array('update_log','filename','comments'), + ); + + $nonmergable_displaytypes = Array(4); + $nonmergable_uitypes = Array('70','69','4'); + + $sql = "SELECT fieldid,typeofdata FROM vtiger_field WHERE tabid = ? and vtiger_field.presence in (0,2) AND block IS NOT NULL"; + $params = array($tabid); + + $where = ''; + + if (isset($nonmergable_field_tab[$tabid]) && count($nonmergable_field_tab[$tabid]) > 0) { + $where .= " AND fieldname NOT IN (". generateQuestionMarks($nonmergable_field_tab[$tabid]) .")"; + array_push($params, $nonmergable_field_tab[$tabid]); + } + + if (count($nonmergable_displaytypes) > 0) { + $where .= " AND displaytype NOT IN (". generateQuestionMarks($nonmergable_displaytypes) .")"; + array_push($params, $nonmergable_displaytypes); + } + if (count($nonmergable_uitypes) > 0) { + $where .= " AND uitype NOT IN ( ". generateQuestionMarks($nonmergable_uitypes) .")" ; + array_push($params, $nonmergable_uitypes); + } + + if (trim($where) != '') { + $sql .= $where; + } + + $res = $adb->pquery($sql, $params); + $log->debug("Exiting getFieldsResultForMerge method ..."); + return $res; +} + +/* Function to get the related tables data + * @param - $module - Primary module name + * @param - $secmodule - Secondary module name + * return Array $rel_array tables and fields to be compared are sent + * */ +function getRelationTables($module,$secmodule){ + global $adb; + $primary_obj = CRMEntity::getInstance($module); + $secondary_obj = CRMEntity::getInstance($secmodule); + + $ui10_query = $adb->pquery("SELECT vtiger_field.tabid AS tabid,vtiger_field.tablename AS tablename, vtiger_field.columnname AS columnname FROM vtiger_field INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid WHERE (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?) OR (vtiger_fieldmodulerel.module=? AND vtiger_fieldmodulerel.relmodule=?)",array($module,$secmodule,$secmodule,$module)); + if($adb->num_rows($ui10_query)>0){ + $ui10_tablename = $adb->query_result($ui10_query,0,'tablename'); + $ui10_columnname = $adb->query_result($ui10_query,0,'columnname'); + $ui10_tabid = $adb->query_result($ui10_query,0,'tabid'); + + if($primary_obj->table_name == $ui10_tablename){ + $reltables = array($ui10_tablename=>array("".$primary_obj->table_index."","$ui10_columnname")); + } else if($secondary_obj->table_name == $ui10_tablename){ + $reltables = array($ui10_tablename=>array("$ui10_columnname","".$secondary_obj->table_index.""),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); + } else { + if(isset($secondary_obj->tab_name_index[$ui10_tablename])){ + $rel_field = $secondary_obj->tab_name_index[$ui10_tablename]; + $reltables = array($ui10_tablename=>array("$ui10_columnname","$rel_field"),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); + } else { + $rel_field = $primary_obj->tab_name_index[$ui10_tablename]; + $reltables = array($ui10_tablename=>array("$rel_field","$ui10_columnname"),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); + } + } + }else { + if(method_exists($primary_obj,setRelationTables)){ + $reltables = $primary_obj->setRelationTables($secmodule); + } else { + $reltables = ''; + } + } + if(is_array($reltables) && !empty($reltables)){ + $rel_array = $reltables; + } else { + $rel_array = array("vtiger_crmentityrel"=>array("crmid","relcrmid"),"".$primary_obj->table_name."" => "".$primary_obj->table_index.""); + } + return $rel_array; +} + +/** + * This function returns no value but handles the delete functionality of each entity. + * Input Parameter are $module - module name, $return_module - return module name, $focus - module object, $record - entity id, $return_id - return entity id. + */ +function DeleteEntity($module,$return_module,$focus,$record,$return_id) { + global $log; + $log->debug("Entering DeleteEntity method ($module, $return_module, $record, $return_id)"); + + if ($module != $return_module && !empty($return_module) && !empty($return_id)) { + $focus->unlinkRelationship($record, $return_module, $return_id); + $focus->trackUnLinkedInfo($return_module, $return_id, $module, $record); + } else { + $focus->trash($module, $record); + } + $log->debug("Exiting DeleteEntity method ..."); +} + +/** + * Function to related two records of different entity types + */ +function relateEntities($focus, $sourceModule, $sourceRecordId, $destinationModule, $destinationRecordIds) { + if(!is_array($destinationRecordIds)) $destinationRecordIds = Array($destinationRecordIds); + foreach($destinationRecordIds as $destinationRecordId) { + $focus->save_related_module($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId); + $focus->trackLinkedInfo($sourceModule, $sourceRecordId, $destinationModule, $destinationRecordId); + } + +} + +/* Function to install Vtlib Compliant modules + * @param - $packagename - Name of the module + * @param - $packagepath - Complete path to the zip file of the Module + */ +function installVtlibModule($packagename, $packagepath, $customized=false) { + global $log; + require_once('vtlib/Vtiger/Package.php'); + require_once('vtlib/Vtiger/Module.php'); + $Vtiger_Utils_Log = true; + $package = new Vtiger_Package(); + + if($package->isLanguageType($packagepath)) { + $package = new Vtiger_Language(); + $package->import($packagepath, true); + return; + } + $module = $package->getModuleNameFromZip($packagepath); + + // Customization + if($package->isLanguageType()) { + require_once('vtlib/Vtiger/Language.php'); + $languagePack = new Vtiger_Language(); + @$languagePack->import($packagepath, true); + return; + } + // END + + $module_exists = false; + $module_dir_exists = false; + if($module == null) { + $log->fatal("$packagename Module zipfile is not valid!"); + } else if(Vtiger_Module::getInstance($module)) { + $log->fatal("$module already exists!"); + $module_exists = true; + } + if($module_exists == false) { + $log->debug("$module - Installation starts here"); + $package->import($packagepath, true); + $moduleInstance = Vtiger_Module::getInstance($module); + if (empty($moduleInstance)) { + $log->fatal("$module module installation failed!"); + } + } +} + +/* Function to update Vtlib Compliant modules + * @param - $module - Name of the module + * @param - $packagepath - Complete path to the zip file of the Module + */ +function updateVtlibModule($module, $packagepath) { + global $log; + require_once('vtlib/Vtiger/Package.php'); + require_once('vtlib/Vtiger/Module.php'); + $Vtiger_Utils_Log = true; + $package = new Vtiger_Package(); + + if($package->isLanguageType($packagepath)) { + require_once('vtlib/Vtiger/Language.php'); + $languagePack = new Vtiger_Language(); + $languagePack->update(null, $packagepath, true); + return; + } + + if($module == null) { + $log->fatal("Module name is invalid"); + } else { + $moduleInstance = Vtiger_Module::getInstance($module); + if($moduleInstance || $package->isModuleBundle($packagepath)) { + $log->debug("$module - Module instance found - Update starts here"); + $package->update($moduleInstance, $packagepath); + } else { + $log->fatal("$module doesn't exists!"); + } + } +} + +/* Function to only initialize the update of Vtlib Compliant modules + * @param - $module - Name of the module + * @param - $packagepath - Complete path to the zip file of the Module + */ +function initUpdateVtlibModule($module, $packagepath) { + global $log; + require_once('vtlib/Vtiger/Package.php'); + require_once('vtlib/Vtiger/Module.php'); + $Vtiger_Utils_Log = true; + $package = new Vtiger_Package(); + + if($module == null) { + $log->fatal("Module name is invalid"); + } else { + $moduleInstance = Vtiger_Module::getInstance($module); + if($moduleInstance) { + $log->debug("$module - Module instance found - Init Update starts here"); + $package->initUpdate($moduleInstance, $packagepath, true); + } else { + $log->fatal("$module doesn't exists!"); + } + } +} + +/** + * this function checks if a given column exists in a given table or not + * @param string $columnName - the columnname + * @param string $tableName - the tablename + * @return boolean $status - true if column exists; false otherwise + */ +function columnExists($columnName, $tableName){ + global $adb; + $columnNames = array(); + $columnNames = $adb->getColumnNames($tableName); + + if(in_array($columnName, $columnNames)){ + return true; + }else{ + return false; + } +} + +/* To get modules list for which work flow and field formulas is permitted*/ +function com_vtGetModules($adb) { + $sql="select distinct vtiger_field.tabid, name + from vtiger_field + inner join vtiger_tab + on vtiger_field.tabid=vtiger_tab.tabid + where vtiger_field.tabid not in(9,10,16,15,8,29) and vtiger_tab.presence = 0 and vtiger_tab.isentitytype=1"; + $it = new SqlResultIterator($adb, $adb->query($sql)); + $modules = array(); + foreach($it as $row) { + if(isPermitted($row->name,'index') == "yes") { + $modules[$row->name] = getTranslatedString($row->name); + } + } + return $modules; +} + +/** + * this function accepts a potential id returns the module name and entity value for the related field + * @param integer $id - the potential id + * @return array $data - the related module name and field value + */ +function getRelatedInfo($id){ + global $adb; + $data = array(); + $sql = "select related_to from vtiger_potential where potentialid=?"; + $result = $adb->pquery($sql, array($id)); + if($adb->num_rows($result)>0){ + $relID = $adb->query_result($result, 0, "related_to"); + $sql = "select setype from vtiger_crmentity where crmid=?"; + $result = $adb->pquery($sql, array($relID)); + if($adb->num_rows($result)>0){ + $setype = $adb->query_result($result, 0, "setype"); + } + $data = array("setype"=>$setype, "relID"=>$relID); + } + return $data; +} + +/** + * this function accepts an ID and returns the entity value for that id + * @param integer $id - the crmid of the record + * @return string $data - the entity name for the id + */ +function getRecordInfoFromID($id){ + global $adb; + $data = array(); + $sql = "select setype from vtiger_crmentity where crmid=?"; + $result = $adb->pquery($sql, array($id)); + if($adb->num_rows($result)>0){ + $setype = $adb->query_result($result, 0, "setype"); + $data = getEntityName($setype, $id); + } + $data = array_values($data); + $data = $data[0]; + return $data; +} + +/** + * this function accepts an tabiD and returns the tablename, fieldname and fieldlabel for email field + * @param integer $tabid - the tabid of current module + * @return string $fields - the array of mail field's tablename, fieldname and fieldlabel + */ +function getMailFields($tabid){ + global $adb; + $fields = array(); + $result = $adb->pquery("SELECT tablename,fieldlabel,fieldname FROM vtiger_field WHERE tabid=? AND uitype IN (13,104)", array($tabid)); + if($adb->num_rows($result)>0){ + $tablename = $adb->query_result($result, 0, "tablename"); + $fieldname = $adb->query_result($result, 0, "fieldname"); + $fieldlabel = $adb->query_result($result, 0, "fieldlabel"); + $fields = array("tablename"=>$tablename,"fieldname"=>$fieldname,"fieldlabel"=>$fieldlabel); + } + return $fields; +} + +/** + * Function to check if a given record exists (not deleted) + * @param integer $recordId - record id + */ +function isRecordExists($recordId) { + global $adb; + $query = "SELECT crmid FROM vtiger_crmentity where crmid=? AND deleted=0"; + $result = $adb->pquery($query, array($recordId)); + if ($adb->num_rows($result)) { + return true; + } + return false; +} + +/** Function to set date values compatible to database (YY_MM_DD) + * @param $value -- value :: Type string + * @returns $insert_date -- insert_date :: Type string + */ +function getValidDBInsertDateValue($value) { + global $log; + $log->debug("Entering getValidDBInsertDateValue(".$value.") method ..."); + $value = trim($value); + $delim = array('/','.'); + foreach ($delim as $delimiter){ + $x = strpos($value, $delimiter); + if($x === false) continue; + else{ + $value=str_replace($delimiter, '-', $value); + break; + } + } + list($y,$m,$d) = explode('-',$value); + if(strlen($y) == 1) $y = '0'.$y; + if(strlen($m) == 1) $m = '0'.$m; + if(strlen($d) == 1) $d = '0'.$d; + $value = implode('-', array($y,$m,$d)); + + if(strlen($y)<4){ + $insert_date = DateTimeField::convertToDBFormat($value); + } else { + $insert_date = $value; + } + + if (preg_match("/^[0-9]{2,4}[-][0-1]{1,2}?[0-9]{1,2}[-][0-3]{1,2}?[0-9]{1,2}$/", $insert_date) == 0) { + return ''; + } + + $log->debug("Exiting getValidDBInsertDateValue method ..."); + return $insert_date; +} + +function getValidDBInsertDateTimeValue($value) { + $value = trim($value); + $valueList = explode(' ',$value); + if(count($valueList) == 2) { + $dbDateValue = getValidDBInsertDateValue($valueList[0]); + $dbTimeValue = $valueList[1]; + if(!empty($dbTimeValue) && strpos($dbTimeValue, ':') === false) { + $dbTimeValue = $dbTimeValue.':'; + } + $timeValueLength = strlen($dbTimeValue); + if(!empty($dbTimeValue) && strrpos($dbTimeValue, ':') == ($timeValueLength-1)) { + $dbTimeValue = $dbTimeValue.'00'; + } + try { + $dateTime = new DateTimeField($dbDateValue.' '.$dbTimeValue); + return $dateTime->getDBInsertDateTimeValue(); + } catch (Exception $ex) { + return ''; + } + } elseif(count($valueList == 1)) { + return getValidDBInsertDateValue($value); + } +} + +/** Function to set the PHP memory limit to the specified value, if the memory limit set in the php.ini is less than the specified value + * @param $newvalue -- Required Memory Limit + */ +function _phpset_memorylimit_MB($newvalue) { + $current = @ini_get('memory_limit'); + if(preg_match("/(.*)M/", $current, $matches)) { + // Check if current value is less then new value + if($matches[1] < $newvalue) { + @ini_set('memory_limit', "{$newvalue}M"); + } + } +} + +/** Function to sanitize the upload file name when the file name is detected to have bad extensions + * @param String -- $fileName - File name to be sanitized + * @return String - Sanitized file name + */ +function sanitizeUploadFileName($fileName, $badFileExtensions) { + + $fileName = preg_replace('/\s+/', '_', $fileName);//replace space with _ in filename + $fileName = rtrim($fileName, '\\/<>?*:"<>|'); + + $fileNameParts = explode(".", $fileName); + $countOfFileNameParts = count($fileNameParts); + $badExtensionFound = false; + + for ($i=0;$i<$countOfFileNameParts;++$i) { + $partOfFileName = $fileNameParts[$i]; + if(in_array(strtolower($partOfFileName), $badFileExtensions)) { + $badExtensionFound = true; + $fileNameParts[$i] = $partOfFileName . 'file'; + } + } + + $newFileName = implode(".", $fileNameParts); + + if ($badExtensionFound) { + $newFileName .= ".txt"; + } + return $newFileName; +} + +/** Function to get the tab meta information for a given id + * @param $tabId -- tab id :: Type integer + * @returns $tabInfo -- array of preference name to preference value :: Type array + */ +function getTabInfo($tabId) { + global $adb; + + $tabInfoResult = $adb->pquery('SELECT prefname, prefvalue FROM vtiger_tab_info WHERE tabid=?', array($tabId)); + $tabInfo = array(); + for($i=0; $i<$adb->num_rows($tabInfoResult); ++$i) { + $prefName = $adb->query_result($tabInfoResult, $i, 'prefname'); + $prefValue = $adb->query_result($tabInfoResult, $i, 'prefvalue'); + $tabInfo[$prefName] = $prefValue; + } +} + +/** Function to return block name + * @param Integer -- $blockid + * @return String - Block Name + */ +function getBlockName($blockid) { + global $adb; + if(!empty($blockid)){ + $block_res = $adb->pquery('SELECT blocklabel FROM vtiger_blocks WHERE blockid = ?',array($blockid)); + if($adb->num_rows($block_res)){ + $blockname = $adb->query_result($block_res,0,'blocklabel'); + return $blockname; + } + } + return ''; +} + +function validateAlphaNumericInput($string){ + preg_match('/^[\w _\-\/]+$/', $string, $matches); + if(count($matches) == 0) { + return false; + } + return true; +} + +function validateServerName($string){ + preg_match('/^[\w\-\.\\/:]+$/', $string, $matches); + if(count($matches) == 0) { + return false; + } + return true; +} + +function validateEmailId($string){ + preg_match('/^[a-zA-Z0-9]+([\_\-\.]*[a-zA-Z0-9]+[\_\-]?)*@[a-zA-Z0-9]+([\_\-]?[a-zA-Z0-9]+)*\.+([\-\_]?[a-zA-Z0-9])+(\.?[a-zA-Z0-9]+)*$/', $string, $matches); + if(count($matches) == 0) { + return false; + } + return true; +} + +function str_rsplit($string, $splitLength) { + $reverseString = strrev($string); + $chunks = str_split($reverseString, $splitLength); + return array_reverse($chunks); +} + +/** + * Function to get the list of Contacts related to an activity + * @param Integer $activityId + * @return Array $contactsList - List of Contact ids, mapped to Contact Names + */ +function getActivityRelatedContacts($activityId) { + $adb = PearDatabase::getInstance(); + + $query = 'SELECT * FROM vtiger_cntactivityrel WHERE activityid=?'; + $result = $adb->pquery($query, array($activityId)); + + $noOfContacts = $adb->num_rows($result); + $contactsList = array(); + for ($i = 0; $i < $noOfContacts; ++$i) { + $contactId = $adb->query_result($result, $i, 'contactid'); + $displayValueArray = getEntityName('Contacts', $contactId); + if (!empty($displayValueArray)) { + foreach ($displayValueArray as $key => $field_value) { + $contact_name = $field_value; + } + } else { + $contact_name=''; + } + $contactsList[$contactId] = $contact_name; + } + return $contactsList; +} + +function isLeadConverted($leadId) { + $adb = PearDatabase::getInstance(); + + $query = 'SELECT converted FROM vtiger_leaddetails WHERE converted = 1 AND leadid=?'; + $params = array($leadId); + + $result = $adb->pquery($query, $params); + + if($result && $adb->num_rows($result) > 0) { + return true; + } + return false; +} + +function getSelectedRecords($input,$module,$idstring,$excludedRecords) { + global $current_user, $adb; + + if($idstring == 'relatedListSelectAll') { + + $recordid = vtlib_purify($input['recordid']); + if($module == 'Accounts') { + $result = getCampaignAccountIds($recordid); + } + if($module == 'Contacts') { + $result = getCampaignContactIds($recordid); + } + if($module == 'Leads') { + $result = getCampaignLeadIds($recordid); + } + $storearray = array(); + for ($i = 0; $i < $adb->num_rows($result); $i++) { + $storearray[] = $adb->query_result($result, $i, 'id'); + } + + $excludedRecords=explode(';',$excludedRecords); + $storearray=array_diff($storearray,$excludedRecords); + + } else if($module == 'Documents') { + + if($input['selectallmode']=='true') { + $result = getSelectAllQuery($input,$module); + $storearray = array(); + $focus = CRMEntity::getInstance($module); + + for ($i = 0; $i < $adb->num_rows($result); $i++) { + $storearray[] = $adb->query_result($result, $i, $focus->table_index); + } + + $excludedRecords = explode(';',$excludedRecords); + $storearray = array_diff($storearray,$excludedRecords); + if($idstring != 'all') { + $storearray = array_merge($storearray,explode(';',$idstring)); + } + $storearray = array_unique($storearray); + + } else { + $storearray = explode(";",$idstring); + } + + } elseif($idstring == 'all') { + + $result = getSelectAllQuery($input,$module); + $storearray = array(); + $focus = CRMEntity::getInstance($module); + + for ($i = 0; $i < $adb->num_rows($result); $i++) { + $storearray[] = $adb->query_result($result, $i, $focus->table_index); + } + + $excludedRecords = explode(';',$excludedRecords); + $storearray = array_diff($storearray,$excludedRecords); + + } else { + $storearray = explode(";",$idstring); + } + + return $storearray; +} + +function getSelectAllQuery($input,$module) { + global $adb,$current_user; + + $viewid = vtlib_purify($input['viewname']); + + if($module == "Calendar") { + $listquery = getListQuery($module); + $oCustomView = new CustomView($module); + $query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,$module); + $where = ''; + if($input['query'] == 'true') { + list($where, $ustring) = split("#@@#",getWhereCondition($module, $input)); + if(isset($where) && $where != '') { + $query .= " AND " .$where; + } + } + } else { + $queryGenerator = new QueryGenerator($module, $current_user); + $queryGenerator->initForCustomViewById($viewid); + + if($input['query'] == 'true') { + $queryGenerator->addUserSearchConditions($input); + } + + $queryGenerator->setFields(array('id')); + $query = $queryGenerator->getQuery(); + + if($module == 'Documents') { + $folderid = vtlib_purify($input['folderidstring']); + $folderid = str_replace(';', ',', $folderid); + $query .= " AND vtiger_notes.folderid in (".$folderid.")"; + } + } + + $result = $adb->pquery($query, array()); + return $result; +} + +function getCampaignAccountIds($id) { + global $adb; + $sql="SELECT vtiger_account.accountid as id FROM vtiger_account + INNER JOIN vtiger_campaignaccountrel ON vtiger_campaignaccountrel.accountid = vtiger_account.accountid + LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid + WHERE vtiger_campaignaccountrel.campaignid = ? AND vtiger_crmentity.deleted=0"; + $result = $adb->pquery($sql, array($id)); + return $result; +} + +function getCampaignContactIds($id) { + global $adb; + $sql="SELECT vtiger_contactdetails.contactid as id FROM vtiger_contactdetails + INNER JOIN vtiger_campaigncontrel ON vtiger_campaigncontrel.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + WHERE vtiger_campaigncontrel.campaignid = ? AND vtiger_crmentity.deleted=0"; + $result = $adb->pquery($sql, array($id)); + return $result; +} + +function getCampaignLeadIds($id) { + global $adb; + $sql="SELECT vtiger_leaddetails.leadid as id FROM vtiger_leaddetails + INNER JOIN vtiger_campaignleadrel ON vtiger_campaignleadrel.leadid = vtiger_leaddetails.leadid + LEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid + WHERE vtiger_campaignleadrel.campaignid = ? AND vtiger_crmentity.deleted=0"; + $result = $adb->pquery($sql, array($id)); + return $result; +} + +/** Function to get the difference between 2 datetime strings or millisecond values */ +function dateDiff($d1, $d2){ + $d1 = (is_string($d1) ? strtotime($d1) : $d1); + $d2 = (is_string($d2) ? strtotime($d2) : $d2); + + $diffSecs = abs($d1 - $d2); + $baseYear = min(date("Y", $d1), date("Y", $d2)); + $diff = mktime(0, 0, $diffSecs, 1, 1, $baseYear); + return array( + "years" => date("Y", $diff) - $baseYear, + "months_total" => (date("Y", $diff) - $baseYear) * 12 + date("n", $diff) - 1, + "months" => date("n", $diff) - 1, + "days_total" => floor($diffSecs / (3600 * 24)), + "days" => date("j", $diff) - 1, + "hours_total" => floor($diffSecs / 3600), + "hours" => date("G", $diff), + "minutes_total" => floor($diffSecs / 60), + "minutes" => (int) date("i", $diff), + "seconds_total" => $diffSecs, + "seconds" => (int) date("s", $diff) + ); +} + +/** +* Function to get the approximate difference between two date time values as string +*/ +function dateDiffAsString($d1, $d2) { + global $currentModule; + + $dateDiff = dateDiff($d1, $d2); + + $years = $dateDiff['years']; + $months = $dateDiff['months']; + $days = $dateDiff['days']; + $hours = $dateDiff['hours']; + $minutes = $dateDiff['minutes']; + $seconds = $dateDiff['seconds']; + + if($years > 0) { + $diffString = "$years ".getTranslatedString('LBL_YEARS',$currentModule); + } elseif($months > 0) { + $diffString = "$months ".getTranslatedString('LBL_MONTHS',$currentModule); + } elseif($days > 0) { + $diffString = "$days ".getTranslatedString('LBL_DAYS',$currentModule); + } elseif($hours > 0) { + $diffString = "$hours ".getTranslatedString('LBL_HOURS',$currentModule); + } elseif($minutes > 0) { + $diffString = "$minutes ".getTranslatedString('LBL_MINUTES',$currentModule); + } else { + $diffString = "$seconds ".getTranslatedString('LBL_SECONDS',$currentModule); + } + return $diffString; +} + +function getMinimumCronFrequency() { + if(file_exists('modules/Ondemand/Ondemand.config.php')) { + require_once('modules/Ondemand/Ondemand.config.php'); + global $VtigerOndemandConfig; + if($VtigerOndemandConfig['MINIMUM_CRON_FREQUENCY'] != '') + return $VtigerOndemandConfig['MINIMUM_CRON_FREQUENCY']; + } + global $MINIMUM_CRON_FREQUENCY; + + if(!empty($MINIMUM_CRON_FREQUENCY)) { + return $MINIMUM_CRON_FREQUENCY; + } + return 15; +} + ?> \ No newline at end of file diff --git a/index.php b/index.php index 8170e88..fc8592c 100644 --- a/index.php +++ b/index.php @@ -23,7 +23,7 @@ global $entityDel; global $display; global $category; -if(version_compare(phpversion(), '5.2.0') < 0) { +if(version_compare(phpversion(), '5.2.0') < 0 or version_compare(phpversion(), '5.4.0','ge') > 0) { insert_charset_header(); $serverPhpVersion = phpversion(); require_once('phpversionfail.php'); @@ -94,6 +94,10 @@ function insert_charset_header() insert_charset_header(); // Create or reestablish the current session session_start(); +$_SESSION['KCFINDER'] = array(); +$_SESSION['KCFINDER']['disabled'] = false; +$_SESSION['KCFINDER']['uploadURL'] = "test/upload"; +$_SESSION['KCFINDER']['uploadDir'] = "../test/upload"; if (!is_file('config.inc.php')) { header("Location: install.php"); @@ -105,12 +109,14 @@ if (!isset($dbconfig['db_hostname']) || $dbconfig['db_status']=='_DB_STAT_') { header("Location: install.php"); exit(); } - + // load up the config_override.php file. This is used to provide default user settings if (is_file('config_override.php')) { require_once('config_override.php'); } +// load global help links +require_once 'config.help.link.php'; /** * Check for vtiger installed version and codebase @@ -215,7 +221,7 @@ $is_module = false; $is_action = false; if(isset($_REQUEST['module'])) { - $module = vtlib_purify($_REQUEST['module']); + $module = $_REQUEST['module']; $dir = @scandir($root_directory."modules"); $temp_arr = Array("CVS","Attic"); $res_arr = @array_intersect($dir,$temp_arr); @@ -597,8 +603,7 @@ if($action == "DetailView") } // set user, theme and language cookies so that login screen defaults to last values -$siteURLParts = parse_url($site_URL); -$cookieDomain = $siteURLParts['host']; +$siteURLParts = parse_url($site_URL); $cookieDomain = $siteURLParts['host']; if (isset($_SESSION['authenticated_user_id'])) { $log->debug("setting cookie ck_login_id_vtiger to ".$_SESSION['authenticated_user_id']); setcookie('ck_login_id_vtiger', $_SESSION['authenticated_user_id'],0,null,$cookieDomain,false,true); @@ -813,22 +818,10 @@ if((!$viewAttachment) && (!$viewAttachment && $action != 'home_rss') && $action { echo $copyrightstatement; - // Status tracking - $statimage = ''; - if($currentModule == 'Users' && empty($current_user->id)) { - global $disable_stats_tracking; - if(isset($disable_stats_tracking) && !empty($disable_stats_tracking)) { - $statimage = ""; - } else { - $statimage = "|"; - } - } // END - echo ""; echo "


"; - echo ""; - echo "
Powered by vtiger CRM $vtiger_current_version© 2004-".date('Y')." vtiger.com | ".$app_strings['LNK_READ_LICENSE']." | ".getTranslatedString('LNK_PRIVACY_POLICY')." $statimage
"; + echo "Powered by ".getTranslatedString('APP_NAME')." $vtiger_current_version"; + echo "© 2004-".date('Y')." $coreBOS_app_name | ".$app_strings['LNK_READ_LICENSE']." | ".getTranslatedString('LNK_PRIVACY_POLICY').""; // echo "
"; // Under the Sugar Public License referenced above, you are required to leave in all copyright statements diff --git a/install/CheckSystem.php b/install/CheckSystem.php index 4220c19..016a73b 100644 --- a/install/CheckSystem.php +++ b/install/CheckSystem.php @@ -56,7 +56,7 @@ $check_mysql_extension = Common_Install_Wizard_Utils::check_mysql_extension(); - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_INSTALLATION_CHECK']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_INSTALLATION_CHECK']?> @@ -69,7 +69,7 @@ $check_mysql_extension = Common_Install_Wizard_Utils::check_mysql_extension(); - +
<?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
@@ -264,7 +264,7 @@ $check_mysql_extension = Common_Install_Wizard_Utils::check_mysql_extension();
- +
www.vtiger.com
diff --git a/install/ConfirmConfig.php b/install/ConfirmConfig.php index d02de59..669a396 100644 --- a/install/ConfirmConfig.php +++ b/install/ConfirmConfig.php @@ -66,7 +66,7 @@ if($next == true) { - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_CONFIRM_SETTINGS']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_CONFIRM_SETTINGS']?> @@ -76,7 +76,7 @@ if($next == true) { - +
<?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
@@ -211,7 +211,7 @@ if($next == true) { - +
www.vtiger.com
diff --git a/install/ConfirmMigrationConfig.php b/install/ConfirmMigrationConfig.php index e77d97d..95be79a 100644 --- a/install/ConfirmMigrationConfig.php +++ b/install/ConfirmMigrationConfig.php @@ -83,7 +83,7 @@ include("modules/Migration/versions.php"); - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_CONFIRM_SETTINGS']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_CONFIRM_SETTINGS']?> @@ -97,7 +97,7 @@ include("modules/Migration/versions.php"); - +
<?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
@@ -225,7 +225,7 @@ include("modules/Migration/versions.php"); - +
www.vtiger.com
diff --git a/install/CreateTables.php b/install/CreateTables.php index 191ee9d..779150b 100644 --- a/install/CreateTables.php +++ b/install/CreateTables.php @@ -54,7 +54,7 @@ session_destroy(); - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_FINISH']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_FINISH']?> @@ -67,7 +67,7 @@ session_destroy(); - +
<?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
@@ -102,7 +102,7 @@ session_destroy();
- vtigercrm-

+



@@ -33,7 +33,7 @@ - +
<?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
@@ -66,24 +66,13 @@ $renamefile = $renameResult['renamefile']; $ins_file_renamed = $renameResult['install_file_renamed']; $ins_dir_renamed = $renameResult['install_directory_renamed']; -// Status tracking -$statimage = ''; @include_once('config.inc.php'); -global $disable_stats_tracking; -if(isset($application_unique_key) && !empty($application_unique_key)) { - if(isset($disable_stats_tracking) && !empty($disable_stats_tracking)) { - $statimage = ""; - } else { - $statimage = "|"; - } -} ?>
- vtigercrm- +
  @@ -121,9 +110,8 @@ if(isset($application_unique_key) && !empty($application_unique_key)) {
    @@ -182,7 +170,7 @@ if(isset($application_unique_key) && !empty($application_unique_key)) {
- | +
www.vtiger.com
diff --git a/install/LicenceAgreement.php b/install/LicenceAgreement.php index 8e3626f..91e8ca5 100644 --- a/install/LicenceAgreement.php +++ b/install/LicenceAgreement.php @@ -12,7 +12,7 @@ - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_INSTALLATION_CHECK']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_INSTALLATION_CHECK']?> @@ -23,7 +23,7 @@ - +
<?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
@@ -91,7 +91,7 @@ - +
www.vtiger.com
diff --git a/install/MigrationComplete.php b/install/MigrationComplete.php index 1abec15..9437b24 100644 --- a/install/MigrationComplete.php +++ b/install/MigrationComplete.php @@ -18,7 +18,7 @@ session_destroy(); - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_FINISH']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_FINISH']?> @@ -30,7 +30,7 @@ session_destroy(); - +
<?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
@@ -106,7 +106,6 @@ $_SESSION['VTIGER_DB_VERSION']= $vtiger_current_version;
  • -
  • @@ -147,7 +146,7 @@ $_SESSION['VTIGER_DB_VERSION']= $vtiger_current_version; - +
    www.vtiger.com
    diff --git a/install/MigrationProcess.php b/install/MigrationProcess.php index 89e423c..0fdaf2a 100644 --- a/install/MigrationProcess.php +++ b/install/MigrationProcess.php @@ -29,7 +29,7 @@ Migration_Utils::copyRequiredFiles($_SESSION['migration_info']['source_directory - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_MIGRATION']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_MIGRATION']?> @@ -47,7 +47,7 @@ if($_REQUEST['migration_start'] != 'true') { - +
    <?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
    @@ -118,7 +118,7 @@ if($_REQUEST['migration_start'] != 'true') { - +
    www.vtiger.com
    diff --git a/install/PreMigrationActions.php b/install/PreMigrationActions.php index b27e2f6..be53b61 100644 --- a/install/PreMigrationActions.php +++ b/install/PreMigrationActions.php @@ -27,7 +27,7 @@ $_SESSION['pre_migration'] = true; - <?php echo $installationStrings['LBL_VTIGER_CRM_5']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_PRE_MIGRATION_TOOLS']?> + <?php echo $installationStrings['APP_NAME']. ' - ' . $installationStrings['LBL_CONFIG_WIZARD']. ' - ' . $installationStrings['LBL_PRE_MIGRATION_TOOLS']?> @@ -124,7 +124,7 @@ $_SESSION['pre_migration'] = true; - +
    <?php echo $installationStrings['LBL_CONFIG_WIZARD']; ?><?php echo $installationStrings['LBL_VTIGER_CRM_5']; ?><?php echo $installationStrings['APP_NAME']; ?>
    @@ -253,7 +253,7 @@ $_SESSION['pre_migration'] = true; - +
    www.vtiger.com
    "; echo ""; - break; - + exit; } } } @@ -678,13 +677,16 @@ class Reports extends CRMEntity{ ); $fields_datatype = array('productid'=>'V', 'serviceid'=>'V', - 'listprice'=>'I', - 'discount'=>'I', - 'quantity'=>'I', + 'listprice'=>'N', + 'discount'=>'N', + 'quantity'=>'N', 'comment'=>'V', ); foreach($fields as $fieldcolname=>$label){ $fieldtypeofdata = $fields_datatype[$fieldcolname]; + if($fieldcolname != 'productid' || $fieldcolname !='serviceid') + $optionvalue = $fieldtablename.$module.":".$fieldcolname.":".$module."_".$label.":".$fieldcolname.":".$fieldtypeofdata; + else $optionvalue = $fieldtablename.":".$fieldcolname.":".$module."_".$label.":".$fieldcolname.":".$fieldtypeofdata; $module_columnlist[$optionvalue] = $label; } @@ -1506,7 +1508,7 @@ function getEscapedColumns($selectedfields) { $typeofdata = explode("~",$columntototalrow["typeofdata"]); - if($typeofdata[0] == "N" || $typeofdata[0] == "I") + if($typeofdata[0] == "N" || $typeofdata[0] == "NN" || $typeofdata[0] == "I" || $typeofdata[0] == "T") { $options = Array(); if(isset($this->columnssummary)) diff --git a/modules/Reports/ScheduledReports.php b/modules/Reports/ScheduledReports.php index 46c38a8..5e489f0 100644 --- a/modules/Reports/ScheduledReports.php +++ b/modules/Reports/ScheduledReports.php @@ -141,7 +141,7 @@ class VTScheduledReport extends Reports { $vtigerMailer->Body = $contents; $vtigerMailer->ContentType = "text/html"; - $baseFileName = preg_replace('/[^a-zA-Z0-9_-\s]/', '', $this->reportname).'_'. preg_replace('/[^a-zA-Z0-9_-\s]/', '', $currentTime); + $baseFileName = utf8_decode(preg_replace('/[^a-zA-Z0-9_-\s]/', '', $this->reportname).'_'. preg_replace('/[^a-zA-Z0-9_-\s]/', '', $currentTime)); $oReportRun = new ReportRun($this->id); $reportFormat = $this->scheduledFormat; @@ -151,14 +151,14 @@ class VTScheduledReport extends Reports { $fileName = $baseFileName.'.pdf'; $filePath = 'storage/'.$fileName; $attachments[$fileName] = $filePath; - $pdf = $oReportRun->getReportPDF(); + $pdf = $oReportRun->getReportPDF(NULL); $pdf->Output($filePath,'F'); } if ($reportFormat == 'excel' || $reportFormat == 'both') { $fileName = $baseFileName.'.xls'; $filePath = 'storage/'.$fileName; $attachments[$fileName] = $filePath; - $oReportRun->writeReportToExcelFile($filePath); + $oReportRun->writeReportToExcelFile($filePath, NULL); } foreach($attachments as $attachmentName => $path) { diff --git a/modules/Reports/language/en_us.lang.php b/modules/Reports/language/en_us.lang.php index 1fb224d..da87224 100644 --- a/modules/Reports/language/en_us.lang.php +++ b/modules/Reports/language/en_us.lang.php @@ -191,8 +191,8 @@ $mod_strings = Array( 'Next 60 Days'=>'Next 60 Days', 'Next 90 Days'=>'Next 90 Days', 'Next 120 Days'=>'Next 120 Days', -'TITLE_VTIGERCRM_CREATE_REPORT' => 'vtiger CRM - Create Report', -'TITLE_VTIGERCRM_PRINT_REPORT' => 'vtiger - Print Report', +'TITLE_VTIGERCRM_CREATE_REPORT' => 'Create Report', +'TITLE_VTIGERCRM_PRINT_REPORT' => 'Print Report', 'NO_FILTER_SELECTED' => 'No filter Selected', 'LBL_GENERATE_NOW'=>'Generate Now', diff --git a/modules/Rss/language/en_us.lang.php b/modules/Rss/language/en_us.lang.php index 9378674..d31b758 100644 --- a/modules/Rss/language/en_us.lang.php +++ b/modules/Rss/language/en_us.lang.php @@ -31,7 +31,7 @@ $mod_strings = Array( 'LBL_STARRED_RSS'=>'Starred Feeds', 'LBL_POP_CRM_RSS'=>'Popular CRM Related Feeds', 'LBL_ALL_RSS_FEEDS'=>'All RSS Feeds', -'LBL_VTIGER_RSS_READER'=>'vtiger RSS Reader', +'LBL_VTIGER_RSS_READER'=>'RSS Reader', 'LBL_MORE'=>'More...', 'LBL_SUBJECT'=>'Subject', diff --git a/modules/Settings/DeleteCustomField.php b/modules/Settings/DeleteCustomField.php index f6df007..6a3cb10 100644 --- a/modules/Settings/DeleteCustomField.php +++ b/modules/Settings/DeleteCustomField.php @@ -87,6 +87,11 @@ if($uitype == 15) { $deltablequery = 'drop table vtiger_'.$adb->sql_escape_string($colName); $adb->pquery($deltablequery, array()); + + $deltablequery_seq = 'drop table vtiger_'.$adb->sql_escape_string($colName).'_seq'; + $adb->pquery($deltablequery_seq, array()); + //Remove picklist dependencies + $adb->query("DELETE FROM vtiger_picklist_dependency WHERE vtiger_picklist_dependency.targetfield = '".$colName."'"); } header("Location:index.php?module=Settings&action=CustomFieldList&fld_module=".$fld_module."&parenttab=Settings"); diff --git a/modules/Settings/EditCompanyDetails.php b/modules/Settings/EditCompanyDetails.php index 44a2d24..d5408f6 100644 --- a/modules/Settings/EditCompanyDetails.php +++ b/modules/Settings/EditCompanyDetails.php @@ -32,9 +32,6 @@ if(isset($_REQUEST['flag']) && $_REQUEST['flag'] != '') case 4: $smarty->assign("ERRORFLAG","".$mod_strings['Problems_in_upload'].". ".$mod_strings['Please_try_again']."
    "); break; - case 5: - $smarty->assign("ERRORFLAG","".$mod_strings['Error_Message']."
    • ".$mod_strings['Invalid_image']."
    • ".$mod_strings['Image_corrupted']."
    "); - break; default: $smarty->assign("ERRORFLAG",""); diff --git a/modules/Settings/LayoutBlockList.php b/modules/Settings/LayoutBlockList.php index 3e13bf5..5d3f33e 100644 --- a/modules/Settings/LayoutBlockList.php +++ b/modules/Settings/LayoutBlockList.php @@ -716,6 +716,11 @@ function deleteCustomField() { if($uitype == 15) { $deltablequery = 'drop table vtiger_'.$adb->sql_escape_string($colName); $adb->pquery($deltablequery, array()); + + $deltablequery_seq = 'drop table vtiger_'.$adb->sql_escape_string($colName).'_seq'; + $adb->pquery($deltablequery_seq, array()); + //Remove picklist dependencies + $adb->query("DELETE FROM vtiger_picklist_dependency WHERE vtiger_picklist_dependency.targetfield = '".$colName."'"); } } diff --git a/modules/Settings/add2db.php b/modules/Settings/add2db.php index 4b89cb7..3fa386e 100644 --- a/modules/Settings/add2db.php +++ b/modules/Settings/add2db.php @@ -18,119 +18,113 @@ $uploaddir = $root_directory . "/test/logo/"; // set this to wherever $saveflag = "true"; $error_flag = ""; $binFile = $_FILES['binFile']['name']; -$imageContent = file_get_contents($_FILES['binFile']['tmp_name']); -if (preg_match('/(<\?(php)?)/i', $imageContent) == 0) { - $imageInfo = getimagesize($_FILES['binFile']['tmp_name']); - $image_extensions_allowed = array('jpeg', 'png', 'jpg', 'pjpeg', 'x-png'); - - if (!empty($imageInfo)) { - if (isset($_REQUEST['binFile_hidden'])) { - $filename = sanitizeUploadFileName(vtlib_purify($_REQUEST['binFile_hidden']), $upload_badext); - } else { - $binFile = sanitizeUploadFileName($binFile, $upload_badext); - $filename = ltrim(basename(" " . $binFile)); - } +$imageInfo = getimagesize($_FILES['binFile']['tmp_name']); +$image_extensions_allowed = array('jpeg', 'png', 'jpg', 'pjpeg', 'x-png'); - $filetype = $_FILES['binFile']['type']; - $filesize = $_FILES['binFile']['size']; - $filetype_array = explode("/", $filetype); - $file_type_val = strtolower($filetype_array[1]); +if (!empty($imageInfo)) { + if (isset($_REQUEST['binFile_hidden'])) { + $filename = sanitizeUploadFileName(vtlib_purify($_REQUEST['binFile_hidden']), $upload_badext); + } else { + $binFile = sanitizeUploadFileName($binFile, $upload_badext); + $filename = ltrim(basename(" " . $binFile)); + } - if ($filesize != 0) { + $filetype = $_FILES['binFile']['type']; + $filesize = $_FILES['binFile']['size']; + $filetype_array = explode("/", $filetype); + $file_type_val = strtolower($filetype_array[1]); + + if ($filesize != 0) { if (in_array($file_type_val, $image_extensions_allowed)) { //Checking whether the file is an image or not - if (stristr($binFile, '.gif') != FALSE) { - $savelogo = "false"; - $error_flag = "1"; - } else { - $savelogo = "true"; - } - } else { + if (stristr($binFile, '.gif') != FALSE) { $savelogo = "false"; $error_flag = "1"; + } else { + $savelogo = "true"; } } else { $savelogo = "false"; - if ($filename != "") - $error_flag = "2"; - } - $errorCode = $_FILES['binFile']['error']; - if ($errorCode == 4) { - $savelogo = "false"; - $error_flag = "5"; - $nologo_specified = "true"; - } else if ($errorCode == 2) { - $error_flag = "3"; - $savelogo = "false"; - $nologo_specified = "false"; - } else if ($errorCode == 3) { - $error_flag = "4"; - $savelogo = "false"; - $nologo_specified = "false"; + $error_flag = "1"; } + } else { + $savelogo = "false"; + if ($filename != "") + $error_flag = "2"; + } + $errorCode = $_FILES['binFile']['error']; + if ($errorCode == 4) { + $savelogo = "false"; + $error_flag = "5"; + $nologo_specified = "true"; + } else if ($errorCode == 2) { + $error_flag = "3"; + $savelogo = "false"; + $nologo_specified = "false"; + } else if ($errorCode == 3) { + $error_flag = "4"; + $savelogo = "false"; + $nologo_specified = "false"; + } - if ($savelogo == "true") { - move_uploaded_file($_FILES["binFile"]["tmp_name"], $uploaddir . $_FILES["binFile"]["name"]); + if ($savelogo == "true") { + move_uploaded_file($_FILES["binFile"]["tmp_name"], $uploaddir . $_FILES["binFile"]["name"]); - $organization_name = vtlib_purify($_REQUEST['organization_name']); - $org_name = vtlib_purify($_REQUEST['org_name']); - $organization_address = from_html($_REQUEST['organization_address']); - $organization_city = from_html($_REQUEST['organization_city']); - $organization_state = from_html($_REQUEST['organization_state']); - $organization_code = from_html($_REQUEST['organization_code']); - $organization_country = from_html($_REQUEST['organization_country']); - $organization_phone = from_html($_REQUEST['organization_phone']); - $organization_fax = from_html($_REQUEST['organization_fax']); - $organization_website = from_html($_REQUEST['organization_website']); + $organization_name = vtlib_purify($_REQUEST['organization_name']); + $org_name = vtlib_purify($_REQUEST['org_name']); + $organization_address = from_html($_REQUEST['organization_address']); + $organization_city = from_html($_REQUEST['organization_city']); + $organization_state = from_html($_REQUEST['organization_state']); + $organization_code = from_html($_REQUEST['organization_code']); + $organization_country = from_html($_REQUEST['organization_country']); + $organization_phone = from_html($_REQUEST['organization_phone']); + $organization_fax = from_html($_REQUEST['organization_fax']); + $organization_website = from_html($_REQUEST['organization_website']); - $organization_logoname = $filename; - if (!isset($organization_logoname)) - $organization_logoname = ""; + $organization_logoname = $filename; + if (!isset($organization_logoname)) + $organization_logoname = ""; - $sql = "SELECT * FROM vtiger_organizationdetails WHERE organizationname = ?"; - $result = $adb->pquery($sql, array($org_name)); - $org_name = decode_html($adb->query_result($result, 0, 'organizationname')); - $org_logo = $adb->query_result($result, 0, 'logoname'); + $sql = "SELECT * FROM vtiger_organizationdetails WHERE organizationname = ?"; + $result = $adb->pquery($sql, array($org_name)); + $org_name = decode_html($adb->query_result($result, 0, 'organizationname')); + $org_logo = $adb->query_result($result, 0, 'logoname'); - if ($org_name == '') { - $organizationId = $adb->getUniqueID('vtiger_organizationdetails'); - $sql = "INSERT INTO vtiger_organizationdetails + if ($org_name == '') { + $organizationId = $this->db->getUniqueID('vtiger_organizationdetails'); + $sql = "INSERT INTO vtiger_organizationdetails (organization_id,organizationname, address, city, state, code, country, phone, fax, website, logoname) values (?,?,?,?,?,?,?,?,?,?)"; - $params = array($organizationId, $organization_name, $organization_address, $organization_city, $organization_state, $organization_code, - $organization_country, $organization_phone, $organization_fax, $organization_website, $organization_logoname); + $params = array($organizationId, $organization_name, $organization_address, $organization_city, $organization_state, $organization_code, + $organization_country, $organization_phone, $organization_fax, $organization_website, $organization_logoname); + } else { + if ($savelogo == "true") { + $organization_logoname = $filename; + } elseif ($savelogo == "false" && $error_flag == "") { + $savelogo = "true"; + $organization_logoname = vtlib_purify($_REQUEST['PREV_FILE']); } else { - if ($savelogo == "true") { - $organization_logoname = $filename; - } elseif ($savelogo == "false" && $error_flag == "") { - $savelogo = "true"; - $organization_logoname = vtlib_purify($_REQUEST['PREV_FILE']); - } else { - $organization_logoname = vtlib_purify($_REQUEST['PREV_FILE']); - } - if ($nologo_specified == "true") { - $savelogo = "true"; - $organization_logoname = $org_logo; - } + $organization_logoname = vtlib_purify($_REQUEST['PREV_FILE']); + } + if ($nologo_specified == "true") { + $savelogo = "true"; + $organization_logoname = $org_logo; + } - $sql = "UPDATE vtiger_organizationdetails + $sql = "UPDATE vtiger_organizationdetails SET organizationname = ?, address = ?, city = ?, state = ?, code = ?, country = ?, phone = ?, fax = ?, website = ?, logoname = ? WHERE organizationname = ?"; - $params = array($organization_name, $organization_address, $organization_city, $organization_state, $organization_code, - $organization_country, $organization_phone, $organization_fax, $organization_website, decode_html($organization_logoname), $org_name); - } - $adb->pquery($sql, $params); + $params = array($organization_name, $organization_address, $organization_city, $organization_state, $organization_code, + $organization_country, $organization_phone, $organization_fax, $organization_website, decode_html($organization_logoname), $org_name); + } + $adb->pquery($sql, $params); - if ($savelogo == "true") { - header("Location: index.php?parenttab=Settings&module=Settings&action=OrganizationConfig"); - } elseif ($savelogo == "false") { - header("Location: index.php?parenttab=Settings&module=Settings&action=EditCompanyDetails&flag=" . $error_flag); - } + if ($savelogo == "true") { + header("Location: index.php?parenttab=Settings&module=Settings&action=OrganizationConfig"); + } elseif ($savelogo == "false") { + header("Location: index.php?parenttab=Settings&module=Settings&action=EditCompanyDetails&flag=" . $error_flag); } - } else { - $error_flag = 2; - header("Location: index.php?parenttab=Settings&module=Settings&action=EditCompanyDetails&flag=" . $error_flag); } -}else{ - $error_flag = 5; +} else { + $error_flag = 2; header("Location: index.php?parenttab=Settings&module=Settings&action=EditCompanyDetails&flag=" . $error_flag); } ?> diff --git a/modules/Settings/language/en_us.lang.php b/modules/Settings/language/en_us.lang.php index ddba086..1646071 100644 --- a/modules/Settings/language/en_us.lang.php +++ b/modules/Settings/language/en_us.lang.php @@ -872,7 +872,7 @@ $mod_strings = Array( 'LBL_SELECT_ENTITY'=>'Select an entity below', 'LBL_CAN_BE_ACCESSED_BY'=>'Can be accessed by', 'LBL_PERMISSIONS'=>'Permissions', -'LBL_DOC_MSWORD'=>'File has to be a Document of type doc/msword', +'LBL_DOC_MSWORD'=>'File has to be a Document of type doc/msword, or OpenOffice/odt or Rich Text Format/rtf', 'LBL_NODOC'=>'No doc File in this directory.Please try again!', //Added for error messages on Company Info. @@ -880,8 +880,6 @@ $mod_strings = Array( 'Error_Message'=>'Error Message', 'Invalid_file'=>'Invalid file OR', 'File_has_no_data'=>'File has no data', -'Invalid_image'=>'Invalid image OR', -'Image_corrupted'=>'Virus detected OR Uploaded Image Corrupted', 'Sorry'=>'Sorry', 'uploaded_file_exceeds_maximum_limit'=>'the uploaded file exceeds the maximum vtiger_filesize limit', 'try_file_smaller'=>'Please try a file smaller than 800000 bytes', @@ -1129,7 +1127,7 @@ $mod_strings = Array( 'VTLIB_LBL_VERIFY_IMPORT_DETAILS'=>'Verify Import Details', 'VTLIB_LBL_MODULE_NAME'=>'Module Name', 'VTLIB_LBL_MODULE_DIR'=>'Module Directory', -'VTLIB_LBL_REQ_VTIGER_VERSION'=>'Req. vtiger version', +'VTLIB_LBL_REQ_VTIGER_VERSION'=>'Required version', 'VTLIB_LBL_LICENSE'=>'License', 'VTLIB_LBL_LICENSE_ACCEPT_AGREEMENT'=>'I accept the license agreement.', 'VTLIB_LBL_PROCEED_WITH_IMPORT'=>'Do you want to proceed with the import?', diff --git a/modules/Settings/savewordtemplate.php b/modules/Settings/savewordtemplate.php old mode 100644 new mode 100755 index aac0dfc..e13140f --- a/modules/Settings/savewordtemplate.php +++ b/modules/Settings/savewordtemplate.php @@ -37,7 +37,8 @@ if(move_uploaded_file($_FILES["binFile"]["tmp_name"],$uploaddir.$_FILES["binFile if($filesize != 0) { - if($file_type_value == "msword" || $file_type_value == "doc" || $file_type_value == "document") + $merge_ext = array('msword','doc','document','rtf','odt','vnd.oasis.opendocument.text','octet-stream','vnd.oasi'); + if (in_array($file_type_value, $merge_ext)) { if($result!=false) { diff --git a/modules/Users/Authenticate.php b/modules/Users/Authenticate.php index 0371854..0a646de 100644 --- a/modules/Users/Authenticate.php +++ b/modules/Users/Authenticate.php @@ -74,15 +74,6 @@ if($focus->is_authenticated()) $_SESSION['authenticated_user_id'] = $focus->id; $_SESSION['app_unique_key'] = $application_unique_key; - global $upload_badext; - //Enabled session variable for KCFINDER - $_SESSION['KCFINDER'] = array(); - $_SESSION['KCFINDER']['disabled'] = false; - $_SESSION['KCFINDER']['uploadURL'] = "test/upload"; - $_SESSION['KCFINDER']['uploadDir'] = "../test/upload"; - $deniedExts = implode(" ", $upload_badext); - $_SESSION['KCFINDER']['deniedExts'] = $deniedExts; - // store the user's theme in the session if(!empty($focus->column_fields["theme"])) { $authenticated_user_theme = $focus->column_fields["theme"]; @@ -154,4 +145,4 @@ else header("Location: index.php"); } -?> \ No newline at end of file +?> diff --git a/modules/Users/DefaultDataPopulator.php b/modules/Users/DefaultDataPopulator.php index dec68f8..6994d9a 100644 --- a/modules/Users/DefaultDataPopulator.php +++ b/modules/Users/DefaultDataPopulator.php @@ -854,7 +854,7 @@ class DefaultDataPopulator extends CRMEntity { $this->db->query("insert into vtiger_field values (23," . $this->db->getUniqueID("vtiger_field") . ",'taxtype','vtiger_invoice',1,'16','hdnTaxType','Tax Type',1,2,'',100,13,$invoicebasicblock,3,'V~O',3,null,'BAS',1)"); $this->db->query("insert into vtiger_field values (23," . $this->db->getUniqueID("vtiger_field") . ",'discount_percent','vtiger_invoice',1,'1','hdnDiscountPercent','Discount Percent',1,2,'',100,13,$invoicebasicblock,3,'N~O',3,null,'BAS',1)"); $this->db->query("insert into vtiger_field values (23," . $this->db->getUniqueID("vtiger_field") . ",'discount_amount','vtiger_invoice',1,'72','hdnDiscountAmount','Discount Amount',1,2,'',100,13,$invoicebasicblock,3,'N~O',3,null,'BAS',1)"); - $this->db->query("insert into vtiger_field values (23," . $this->db->getUniqueID("vtiger_field") . ",'s_h_amount','vtiger_invoice',1,'72','hdnS_H_Amount','S&H Amount',1,2,'',100,14,57,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23," . $this->db->getUniqueID("vtiger_field") . ",'s_h_amount','vtiger_invoice',1,'72','hdnS_H_Amount','S&H Amount',1,2,'',100,14,67,3,'N~O',3,null,'BAS',1)"); $this->db->query("insert into vtiger_field values (23," . $this->db->getUniqueID("vtiger_field") . ",'accountid','vtiger_invoice',1,'73','account_id','Account Name',1,2,'',100,14,$invoicebasicblock,1,'I~M',3,null,'BAS',1)"); $this->db->query("insert into vtiger_field values (23," . $this->db->getUniqueID("vtiger_field") . ",'invoicestatus','vtiger_invoice',1,'15','invoicestatus','Status',1,2,'',100,15,$invoicebasicblock,1,'V~O',3,null,'BAS',1)"); @@ -1860,8 +1860,8 @@ Should any need arise,please do give us a call.'; //Insert into vtiger_organizationdetails vtiger_table $organizationId = $this->db->getUniqueID('vtiger_organizationdetails'); $this->db->query("insert into vtiger_organizationdetails(organization_id,organizationname,address,city,state,country,code,phone,fax,website,logoname) - values ($organizationId,'vtiger',' 40-41-42, Sivasundar Apartments, Flat D-II, Shastri Street, Velachery','Chennai', - 'Tamil Nadu','India','600 042','+91-44-5202-1990','+91-44-5202-1990','www.vtiger.com','vtiger-crm-logo.gif')"); + values ($organizationId,'Your Company',' Your Address','Your City', + 'Your State','Your Country','ZIP CODE','+99-98-7654-3210','+99-98-7654-3210','www.your-company.tld','app-logo.png')"); $this->db->query("insert into vtiger_actionmapping values(0,'Save',0)"); diff --git a/modules/Users/Save.php b/modules/Users/Save.php index 1dfef68..bfdf968 100644 --- a/modules/Users/Save.php +++ b/modules/Users/Save.php @@ -51,8 +51,7 @@ if(isset($_REQUEST['dup_check']) && $_REQUEST['dup_check'] != '') die; } } -if($_REQUEST['user_role'] != '' && !is_admin($current_user) && $_REQUEST['user_role'] != $current_user->roleid){ - +if($_REQUEST['user_role'] != '' && !is_admin($current_user) && $_REQUEST['user_role'] != $current_user->roleid){ $log->fatal("SECURITY:Non-Admin user:". $current_user->id . " attempted to change user role"); echo ""; echo " + + + + '; + $success_query_array[$success_query_count++] = $query; + $log->debug("Query Success ==> $query"); + } else { + echo ' + + + + + '; + $failure_query_array[$failure_query_count++] = $query; + $log->debug("Query Failed ==> $query \n Error is ==> [".$adb->database->ErrorNo()."]".$adb->database->ErrorMsg()); + } +} +function putMsg($msg) { + echo ''; +} + +echo "
    "; @@ -106,7 +105,7 @@ if($_REQUEST['changepassword'] == 'true') { $focus->retrieve_entity_info($_REQUEST['record'],'Users'); $focus->id = vtlib_purify($_REQUEST['record']); if (isset($_REQUEST['new_password'])) { - if (!$focus->change_password($_REQUEST['old_password'], $_REQUEST['new_password'])) { + if (!$focus->change_password(vtlib_purify($_REQUEST['old_password']), vtlib_purify($_REQUEST['new_password']))) { header("Location: index.php?action=Error&module=Users&error_string=".urlencode($focus->error_string)); exit; } @@ -215,4 +214,4 @@ if ($error_str != '') { header($location); -?> \ No newline at end of file +?> diff --git a/modules/Users/Users.php b/modules/Users/Users.php index 7605027..bb38b4c 100644 --- a/modules/Users/Users.php +++ b/modules/Users/Users.php @@ -578,7 +578,11 @@ class Users extends CRMEntity { global $adb; $query = "SELECT id from vtiger_users where user_name=? AND deleted=0"; $result =$adb->pquery($query, array($user_name)); + if ($result and $adb->num_rows($result)>0) { $userid = $adb->query_result($result,0,'id'); + } else { + $userid = 0; + } return $userid; } @@ -1411,6 +1415,9 @@ class Users extends CRMEntity { //delete from user vtiger_table; $sql = "delete from vtiger_users where id=?"; $adb->pquery($sql, array($userId)); + //Delete user extension in asterisk. + $sql = "delete from vtiger_asteriskextensions where userid=?"; + $adb->pquery($sql, array($userId)); } /** diff --git a/modules/Users/about_us.php b/modules/Users/about_us.php index c60b30c..00bc220 100644 --- a/modules/Users/about_us.php +++ b/modules/Users/about_us.php @@ -35,7 +35,11 @@ global $mod_strings; <?php echo $mod_strings['TITLE_VTIGER_CRM_5'];?> - + "; echo ""; diff --git a/modules/com_vtiger_workflow/VTSimpleTemplate.inc b/modules/com_vtiger_workflow/VTSimpleTemplate.inc index bd22f99..87db3f4 100644 --- a/modules/com_vtiger_workflow/VTSimpleTemplate.inc +++ b/modules/com_vtiger_workflow/VTSimpleTemplate.inc @@ -80,7 +80,7 @@ class VTSimpleTemplate{ } function parseTemplate(){ - return preg_replace_callback('/\\$(\w+|\((\w+) : \(([_\w]+)\) (\w+)\)),?/', array($this,"matchHandler"), $this->template); + return preg_replace_callback('/\\$(\w+|\((\w+) : \(([_\w]+)\) (\w+)\))/', array($this,"matchHandler"), $this->template); } function getMetaValue($fieldname){ diff --git a/modules/com_vtiger_workflow/VTTaskManager.inc b/modules/com_vtiger_workflow/VTTaskManager.inc index 659f1c7..cd24b7f 100644 --- a/modules/com_vtiger_workflow/VTTaskManager.inc +++ b/modules/com_vtiger_workflow/VTTaskManager.inc @@ -172,9 +172,11 @@ } public function formatTimeForTimePicker($time) { + $AM_PM = array('am', 'pm'); + if (in_array(strtolower(substr($time, -2)),$AM_PM)) + return $time; // ya tiene el formato correcto, devolverlo sin más list($h, $m, $s) = explode(':', $time); $mn = str_pad($m - $m % 15, 2, 0, STR_PAD_LEFT); - $AM_PM = array('am', 'pm'); return str_pad(($h%12), 2, 0, STR_PAD_LEFT).':'.$mn.$AM_PM[($h/12)%2]; } diff --git a/modules/com_vtiger_workflow/deletetask.php b/modules/com_vtiger_workflow/deletetask.php index db34a21..df98b9a 100644 --- a/modules/com_vtiger_workflow/deletetask.php +++ b/modules/com_vtiger_workflow/deletetask.php @@ -18,7 +18,7 @@ require_once('VTWorkflowUtils.php'); $util = new VTWorkflowUtils(); $module = new VTWorkflowApplication("deltetask"); $mod = return_module_language($current_language, $module->name); - + $request = vtlib_purify($request); // this cleans all values of the array if(!$util->checkAdminAccess()){ $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); @@ -29,7 +29,7 @@ require_once('VTWorkflowUtils.php'); $wm->deleteTask($request['task_id']); if(isset($request["return_url"])){ - $returnUrl= vtlib_purify($request["return_url"]); + $returnUrl=$request["return_url"]; }else{ $returnUrl=$module->editWorkflowUrl($wf->id); } diff --git a/modules/com_vtiger_workflow/edittask.php b/modules/com_vtiger_workflow/edittask.php index 43e60a9..c4d7831 100644 --- a/modules/com_vtiger_workflow/edittask.php +++ b/modules/com_vtiger_workflow/edittask.php @@ -20,6 +20,7 @@ require_once("VTWorkflowUtils.php"); function vtTaskEdit($adb, $request, $current_language, $app_strings){ global $theme; $util = new VTWorkflowUtils(); + $request = vtlib_purify($request); // this cleans all values of the array $image_path = "themes/$theme/images/"; $module = new VTWorkflowApplication('edittask'); @@ -37,11 +38,10 @@ require_once("VTWorkflowUtils.php"); $smarty->assign('edit',isset($request["task_id"])); if(isset($request["task_id"])){ $task = $tm->retrieveTask($request["task_id"]); - $taskClass = get_class($task); $workflowId=$task->workflowId; }else{ $workflowId = $request["workflow_id"]; - $taskClass = vtlib_purifyForSql($request["task_type"]); + $taskClass = $request["task_type"]; $task = $tm->createTask($taskClass, $workflowId); } @@ -61,15 +61,12 @@ require_once("VTWorkflowUtils.php"); $smarty->assign("workflow", $workflow); - $smarty->assign("returnUrl", vtlib_purify($request["return_url"])); + $smarty->assign("returnUrl", $request["return_url"]); $smarty->assign("task", $task); $smarty->assign("taskType", $taskClass); - $smarty->assign("saveType", vtlib_purify($request['save_type'])); - - $taskTypeInstance = VTTaskType::getInstanceFromTaskType($taskClass); - $taskTemplateClass = $tm->retrieveTemplatePath($module->name, $taskTypeInstance); - $smarty->assign("taskTemplate", $taskTemplateClass); - + $smarty->assign("saveType", $request['save_type']); + $taskClass = get_class($task); + $smarty->assign("taskTemplate", "{$module->name}/taskforms/$taskClass.tpl"); $et = VTWSEntityType::usingGlobalCurrentUser($workflow->moduleName); $smarty->assign("entityType", $et); $smarty->assign('entityName', $workflow->moduleName); @@ -123,13 +120,6 @@ require_once("VTWorkflowUtils.php"); $smarty->assign("PAGE_NAME", $mod['LBL_EDIT_TASK']); $smarty->assign("PAGE_TITLE", $mod['LBL_EDIT_TASK_TITLE']); - $users = $group = array(); - $users = get_user_array(); - $group = get_group_array(); - foreach($group as $id => $name) { - $users[$id] = $name; - } - $smarty->assign('ASSIGNED_TO', $users); $smarty->assign("module", $module); $smarty->display("{$module->name}/EditTask.tpl"); } diff --git a/modules/com_vtiger_workflow/editworkflow.php b/modules/com_vtiger_workflow/editworkflow.php index b4547c1..2537ecd 100644 --- a/modules/com_vtiger_workflow/editworkflow.php +++ b/modules/com_vtiger_workflow/editworkflow.php @@ -19,11 +19,10 @@ require_once("VTTaskManager.inc"); require_once("VTWorkflowApplication.inc"); require_once "VTWorkflowTemplateManager.inc"; require_once "VTWorkflowUtils.php"; -require_once 'config.help.link.php'; function vtWorkflowEdit($adb, $request, $requestUrl, $current_language, $app_strings){ - global $theme, $helpLinks; + global $theme; $util = new VTWorkflowUtils(); $image_path = "themes/$theme/images/"; @@ -83,7 +82,7 @@ function vtWorkflowEdit($adb, $request, $requestUrl, $current_language, $app_str $smarty->assign("saveType", isset($workflow->id)?"edit":"new"); $smarty->assign("module", $module); - $smarty->assign("WORKFLOW_TRIGGER_TYPES_HELP_LINK", $helpLinks['WORKFLOW_TRIGGER_TYPES']); + $smarty->assign("WORKFLOW_TRIGGER_TYPES_HELP_LINK", WORKFLOW_TRIGGER_TYPES); $smarty->display("{$module->name}/EditWorkflow.tpl"); } diff --git a/modules/com_vtiger_workflow/savetask.php b/modules/com_vtiger_workflow/savetask.php index ae334b3..f0af66d 100644 --- a/modules/com_vtiger_workflow/savetask.php +++ b/modules/com_vtiger_workflow/savetask.php @@ -18,7 +18,7 @@ require_once("VTWorkflowApplication.inc"); $util = new VTWorkflowUtils(); $module = new VTWorkflowApplication("savetask"); $mod = return_module_language($current_language, $module->name); - + $request = vtlib_purify($request); // this cleans all values of the array if(!$util->checkAdminAccess()){ $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); @@ -29,7 +29,7 @@ require_once("VTWorkflowApplication.inc"); if(isset($request["task_id"])){ $task = $tm->retrieveTask($request["task_id"]); }else{ - $taskType = vtlib_purifyForSql($request["task_type"]); + $taskType = $request["task_type"]; $workflowId = $request["workflow_id"]; $task = $tm->createTask($taskType, $workflowId); } @@ -59,8 +59,8 @@ require_once("VTWorkflowApplication.inc"); } $tm->saveTask($task); - if(isset(vtlib_purify($request["return_url"]))) { - $returnUrl= vtlib_purify($request["return_url"]); + if(isset($request["return_url"])){ + $returnUrl=$request["return_url"]; }else{ $returnUrl=$module->editTaskUrl($task->id); } diff --git a/modules/com_vtiger_workflow/savetemplate.php b/modules/com_vtiger_workflow/savetemplate.php index 0275e0c..d5a4769 100644 --- a/modules/com_vtiger_workflow/savetemplate.php +++ b/modules/com_vtiger_workflow/savetemplate.php @@ -20,21 +20,21 @@ function vtSaveWorkflowTemplate($adb, $request){ $util = new VTWorkflowUtils(); $module = new VTWorkflowApplication("savetemplate"); $mod = return_module_language($current_language, $module->name); - + $request = vtlib_purify($request); // this cleans all values of the array if(!$util->checkAdminAccess()){ $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); return; } - $title = vtlib_purifyForSql($request['title']); + $title = $request['title']; $workflowId = $request['workflow_id']; $wfs = new VTworkflowManager($adb); $workflow = $wfs->retrieve($workflowId); $tm = new VTWorkflowTemplateManager($adb); $tpl = $tm->newTemplate($title, $workflow); $tm->saveTemplate($tpl); - $returnUrl = vtlib_purify($request['return_url']); + $returnUrl = $request['return_url']; ?> Return \ No newline at end of file diff --git a/modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc b/modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc index efbb1de..b45bcf5 100644 --- a/modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc +++ b/modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc @@ -64,9 +64,8 @@ class VTCreateTodoTask extends VTTask{ 'taskpriority'=>$this->priority, 'taskstatus'=>$this->status, 'assigned_user_id'=>$userId, - 'time_start'=> $startDate->getDisplayTime(), - 'sendnotification'=>($this->sendNotification!='' && $this->sendNotification!='N')? - true: false, + 'time_start'=> self::conv12to24hour($this->time), + 'sendnotification'=>($this->sendNotification!='' && $this->sendNotification!='N')? true: false, 'date_start'=>$date, 'due_date'=>$date, 'visibility'=>'all', diff --git a/phpversionfail.php b/phpversionfail.php index 2b335f7..172ddf6 100644 --- a/phpversionfail.php +++ b/phpversionfail.php @@ -7,13 +7,13 @@ * Portions created by vtiger are Copyright (C) vtiger. * All Rights Reserved. ********************************************************************************/ - +include_once 'vtigerversion.php'; ?> - vtiger CRM 5 - PHP Version Check + <?php echo $coreBOS_app_name; ?> - PHP Version Check @@ -23,7 +23,7 @@ - +
     vtiger CRM 5<?php echo $coreBOS_app_name; ?>
    @@ -36,7 +36,7 @@
    - PHP 5.2.x or above is required. Your current PHP version is + PHP 5.2.x or PHP 5.3.x is required. Your current PHP version is
    - Kindly upgrade the PHP installation, and try again!
    + Kindly adapt your PHP installation, and try again!
    @@ -68,7 +68,7 @@ - +
    www.vtiger.com
    diff --git a/schema/.htaccess b/schema/.htaccess new file mode 100644 index 0000000..e019832 --- /dev/null +++ b/schema/.htaccess @@ -0,0 +1 @@ +deny from all diff --git a/backup/.htaccess b/backup/.htaccess new file mode 100644 index 0000000..e019832 --- /dev/null +++ b/backup/.htaccess @@ -0,0 +1 @@ +deny from all diff --git a/logs/.htaccess b/logs/.htaccess new file mode 100644 index 0000000..e019832 --- /dev/null +++ b/logs/.htaccess @@ -0,0 +1 @@ +deny from all diff --git a/soap/customerportal.php b/soap/customerportal.php old mode 100644 new mode 100755 index 26be456..92178f8 --- a/soap/customerportal.php +++ b/soap/customerportal.php @@ -448,19 +448,19 @@ function get_combo_values($input_array) if($RowCount > 0){ $admin_role = $adb->query_result($roleres,0,'roleid'); } - $result1 = $adb->pquery("select vtiger_ticketpriorities.ticketpriorities from vtiger_ticketpriorities inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketpriorities.picklist_valueid and vtiger_role2picklist.roleid='$admin_role'", array()); + $result1 = $adb->pquery("select vtiger_ticketpriorities.ticketpriorities from vtiger_ticketpriorities inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketpriorities.picklist_valueid and vtiger_role2picklist.roleid='$admin_role' order by sortorderid", array()); for($i=0;$i<$adb->num_rows($result1);$i++) { $output['ticketpriorities']['ticketpriorities'][$i] = $adb->query_result($result1,$i,"ticketpriorities"); } - $result2 = $adb->pquery("select vtiger_ticketseverities.ticketseverities from vtiger_ticketseverities inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketseverities.picklist_valueid and vtiger_role2picklist.roleid='$admin_role'", array()); + $result2 = $adb->pquery("select vtiger_ticketseverities.ticketseverities from vtiger_ticketseverities inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketseverities.picklist_valueid and vtiger_role2picklist.roleid='$admin_role' order by sortorderid", array()); for($i=0;$i<$adb->num_rows($result2);$i++) { $output['ticketseverities']['ticketseverities'][$i] = $adb->query_result($result2,$i,"ticketseverities"); } - $result3 = $adb->pquery("select vtiger_ticketcategories.ticketcategories from vtiger_ticketcategories inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketcategories.picklist_valueid and vtiger_role2picklist.roleid='$admin_role'", array()); + $result3 = $adb->pquery("select vtiger_ticketcategories.ticketcategories from vtiger_ticketcategories inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_ticketcategories.picklist_valueid and vtiger_role2picklist.roleid='$admin_role' order by sortorderid", array()); for($i=0;$i<$adb->num_rows($result3);$i++) { $output['ticketcategories']['ticketcategories'][$i] = $adb->query_result($result3,$i,"ticketcategories"); @@ -640,6 +640,17 @@ function get_tickets_list($input_array) { //To avoid SQL injection we are type casting as well as bound the id variable. $id = (int) vtlib_purify($input_array['id']); + + $only_mine = $input_array['onlymine']; + $where = vtlib_purifyForSql($input_array['where']); //addslashes is already added with where condition fields in portal itself + $match = $input_array['match']; + $sessionid = $input_array['sessionid']; + + if(!validateSession($id,$sessionid)) + return null; + + //To avoid SQL injection we are type casting as well as bound the id variable. + $id = (int) vtlib_purify($input_array['id']); $only_mine = $input_array['onlymine']; $where = vtlib_purifyForSql($input_array['where']); //addslashes is already added with where condition fields in portal itself @@ -1400,9 +1411,9 @@ function validateSession($id, $sessionid) { global $adb; $adb->println("Inside function validateSession($id, $sessionid)"); - + if(empty($sessionid)) return false; - + $server_sessionid = getServerSessionId($id); $adb->println("Checking Server session id and customer input session id ==> $server_sessionid == $sessionid"); @@ -1435,7 +1446,7 @@ function getServerSessionId($id) $result = $adb->pquery($query, array($id)); if($adb->num_rows($result) > 0) { $sessionid = $adb->query_result($result,0,'sessionid'); - Vtiger_Soap_CustomerPortal::updateSessionId($id, $sessionid); + Vtiger_Soap_CustomerPortal::updateSessionId($id, $sessionid); } } return $sessionid; @@ -1543,7 +1554,7 @@ function get_list_values($id,$module,$sessionid,$only_mine='true') if($check == false){ return array("#MODULE INACTIVE#"); } - + //To avoid SQL injection we are type casting as well as bound the id variable. $id = (int) vtlib_purify($id); $user = new Users(); @@ -1672,6 +1683,7 @@ function get_list_values($id,$module,$sessionid,$only_mine='true') $output[0][$module]['head'][0][$i]['fielddata'] = $fieldlabel; $fieldvalue = $adb->query_result($res,$j,$fieldname); + $fieldValuesToRound = array('total','subtotal','adjustment','discount_amount','s_h_amount','pre_tax_total','received','balance','unit_price'); if($module == 'Quotes') { @@ -1680,6 +1692,9 @@ function get_list_values($id,$module,$sessionid,$only_mine='true') $filename = $fieldid.'_Quotes.pdf'; $fieldvalue = ''.$fieldvalue.''; } + if(in_array($fieldname, $fieldValuesToRound)){ + $fieldvalue = round($fieldvalue, 2); + } if($fieldname == 'total'){ $sym = getCurrencySymbol($res,$j,'currency_id'); $fieldvalue = $sym.$fieldvalue; @@ -1692,6 +1707,9 @@ function get_list_values($id,$module,$sessionid,$only_mine='true') $filename = $fieldid.'_Invoice.pdf'; $fieldvalue = ''.$fieldvalue.''; } + if(in_array($fieldname, $fieldValuesToRound)){ + $fieldvalue = round($fieldvalue, 2); + } if($fieldname == 'total'){ $sym = getCurrencySymbol($res,$j,'currency_id'); $fieldvalue = $sym.$fieldvalue; @@ -1744,6 +1762,9 @@ function get_list_values($id,$module,$sessionid,$only_mine='true') $fieldvalue = 'No'; } } + if(in_array($fieldname, $fieldValuesToRound)){ + $fieldvalue = round($fieldvalue, 2); + } if($fieldname == 'unit_price'){ $sym = getCurrencySymbol($res,$j,'currency_id'); $fieldvalue = $sym.$fieldvalue; @@ -2053,9 +2074,14 @@ function get_product_list_values($id,$modulename,$sessionid,$only_mine='true') if($check == false){ return array("#MODULE INACTIVE#"); } + + //To avoid SQL injection we are type casting as well as bound the id variable. + $id = (int) vtlib_purify($id); $user = new Users(); $userid = getPortalUserid(); $current_user = $user->retrieveCurrentUserInfoFromFile($userid); + //To avoid SQL injection we are type casting as well as bound the id variable + $id = (int) vtlib_purify($id); $entity_ids_list = array(); $show_all=show_all($modulename); @@ -2124,6 +2150,7 @@ function get_product_list_values($id,$modulename,$sessionid,$only_mine='true') where vtiger_inventoryproductrel.productid = vtiger_products.productid AND vtiger_crmentity.deleted=0 and (accountid in (". generateQuestionMarks($entity_ids_list) .") or contactid in (". generateQuestionMarks($entity_ids_list) ."))"; $params[] = array($entity_ids_list,$entity_ids_list); } + $fieldValuesToRound = array('unit_price','weight','commissionrate','qtyinstock'); for($k=0;$kpquery($query[$k],$params[$k]); @@ -2142,6 +2169,9 @@ function get_product_list_values($id,$modulename,$sessionid,$only_mine='true') $fieldvalue = $adb->query_result($res[$k],$j,$fieldname); $fieldid = $adb->query_result($res[$k],$j,'productid'); + if(in_array($fieldname, $fieldValuesToRound)){ + $fieldvalue = round($fieldvalue, 2); + } if($fieldname == 'entityid') { $crmid = $fieldvalue; $module = $adb->query_result($res[$k],$j,'setype'); @@ -2213,11 +2243,12 @@ function get_details($id,$module,$customerid,$sessionid) } else if($module == 'Documents'){ $query = "SELECT - vtiger_notes.*,vtiger_crmentity.*,vtiger_attachmentsfolder.foldername + vtiger_notes.*,vtiger_crmentity.*,vtiger_attachmentsfolder.foldername,vtiger_notescf.* FROM vtiger_notes INNER JOIN vtiger_crmentity on vtiger_crmentity.crmid = vtiger_notes.notesid LEFT JOIN vtiger_attachmentsfolder ON vtiger_notes.folderid = vtiger_attachmentsfolder.folderid + LEFT JOIN vtiger_notescf ON vtiger_notescf.notesid = vtiger_notes.notesid where vtiger_notes.notesid=(". generateQuestionMarks($id) .") AND vtiger_crmentity.deleted=0"; } else if($module == 'HelpDesk'){ @@ -2282,7 +2313,7 @@ function get_details($id,$module,$customerid,$sessionid) INNER JOIN vtiger_crmentity ON vtiger_assets.assetsid = vtiger_crmentity.crmid INNER JOIN vtiger_assetscf - ON vtiger_assets.assetsid = vtiger_assets.assetsid + ON vtiger_assetscf.assetsid = vtiger_assets.assetsid WHERE vtiger_crmentity.deleted = 0 AND vtiger_assets.assetsid = (". generateQuestionMarks($id) .")"; } else if ($module == 'Project') { $query = "SELECT vtiger_project.*, vtiger_projectcf.*, vtiger_crmentity.* @@ -2449,6 +2480,7 @@ function get_details($id,$module,$customerid,$sessionid) } if($fieldname == 'unit_price'){ $sym = getCurrencySymbol($res,0,'currency_id'); + $fieldvalue = round($fieldvalue, 2); $fieldvalue = $sym.$fieldvalue; } $output[0][$module][$i]['fieldvalue'] = $fieldvalue; @@ -3032,6 +3064,8 @@ function get_service_list_values($id,$modulename,$sessionid,$only_mine='true') getFieldVisibilityPermission('Services',$current_user->id,$fieldname); } + $fieldValuesToRound = array('unit_price','commissionrate'); + for($k=0;$kpquery($query[$k],$params[$k]); @@ -3051,6 +3085,9 @@ function get_service_list_values($id,$modulename,$sessionid,$only_mine='true') $fieldvalue = $adb->query_result($res[$k],$j,$fieldname); $fieldid = $adb->query_result($res[$k],$j,'serviceid'); + if(in_array($fieldname, $fieldValuesToRound)){ + $fieldvalue = round($fieldvalue, 2); + } if($fieldname == 'entityid') { $crmid = $fieldvalue; $module = $adb->query_result($res[$k],$j,'setype'); @@ -3230,7 +3267,6 @@ function getDefaultAssigneeId() { } } return $defaultassignee; - $log->debug("Exiting customerportal function getPortalUserid"); } /* Begin the HTTP listener service and exit. */ diff --git a/soap/firefoxtoolbar.php b/soap/firefoxtoolbar.php index 6e9ea4a..4aadc92 100644 --- a/soap/firefoxtoolbar.php +++ b/soap/firefoxtoolbar.php @@ -905,7 +905,7 @@ function getServerSessionId($id) $id = (int) $id; $query = "select * from vtiger_soapservice where type='FireFox' and id={$id}"; - $sessionid = $adb->query_result($adb->pquery($query, array()),0,'sessionid'); + $sessionid = $adb->query_result($adb->query($query),0,'sessionid'); return $sessionid; } diff --git a/soap/vtigerolservice.php b/soap/vtigerolservice.php index b0408f5..7e3e29e 100644 --- a/soap/vtigerolservice.php +++ b/soap/vtigerolservice.php @@ -287,11 +287,11 @@ function SearchContactsByEmail($username,$session,$emailaddress) $seed_contact = new Contacts(); $output_list = Array(); - + //To avoid Blind SQL injection we are validating the Email address. if(filter_var($emailaddress, FILTER_VALIDATE_EMAIL) == false ) return null; - $response = $seed_contact->get_searchbyemailid($username,$emailaddress); + $response = $seed_contact->get_searchbyemailid($username,$emailaddress); $contactList = $response['list']; // create a return array of names and email addresses. @@ -461,13 +461,13 @@ function CheckActivityPermission($username,$session) function AddEmailAttachment($emailid,$filedata,$filename,$filesize,$filetype,$username,$session) { if(!validateSession($username,$session)) return null; - + if(empty($emailid)) return null; - - global $adb; + + global $adb, $upload_badext; require_once('modules/Users/Users.php'); require_once('include/utils/utils.php'); - $filename = vtlib_purifyForSql(preg_replace('/\s+/', '_', $filename));//replace space with _ in filename + $filename = vtlib_purifyForSql(sanitizeUploadFileName(str_replace('..','_',$filename), $upload_badext)); // Avoid relative file path attacks. $date_var = date('Y-m-d H:i:s'); $seed_user = new Users(); @@ -1387,7 +1387,7 @@ function validateSession($username, $sessionid) $id = $seed_user->retrieve_user_id($username); if(empty($sessionid)) return false; - + $server_sessionid = getServerSessionId($id); $adb->println("Checking Server session id and customer input session id ==> $server_sessionid == $sessionid"); diff --git a/soap/webforms.php.deprecated b/soap/webforms.php.deprecated deleted file mode 100644 index 33ed94f..0000000 --- a/soap/webforms.php.deprecated +++ /dev/null @@ -1,199 +0,0 @@ -configureWSDL('vtigersoap'); - - -$server->register( - 'create_lead_from_webform', - array( - 'lastname'=>'xsd:string', - 'email'=>'xsd:string', - 'phone'=>'xsd:string', - 'company'=>'xsd:string', - 'country'=>'xsd:string', - 'description'=>'xsd:string', - 'assigned_user_id'=>'xsd:string' - ), - array('return'=>'xsd:string'), - $NAMESPACE); - -$server->register( - 'create_contact_from_webform', - array( - 'first_name'=>'xsd:string', - 'last_name'=>'xsd:string', - 'email_address'=>'xsd:string', - 'home_phone'=>'xsd:string', - 'department'=>'xsd:string', - 'description'=>'xsd:string', - 'assigned_user_id'=>'xsd:string' - ), - array('return'=>'xsd:string'), - $NAMESPACE); - -$server->register( - 'unsubscribe_email', - array( - 'email_address'=>'xsd:string' - ), - array('return'=>'xsd:string'), - $NAMESPACE); - - -/** function used to create lead from webform from the passed details - * @param string $lastname - last name of the lead - * @param string $email - email of the lead - * @param string $phone - phone number of the lead - * @param string $company - company name of the lead - * @param string $country - country name of the lead - * @param string $description - description to create a lead - * @param int $assigned_user_id - assigned to user for the lead - * return message success or failure about the lead creation - */ -function create_lead_from_webform($lastname, $email, $phone, $company, $country, $description, $assigned_user_id) -{ - global $adb; - $adb->println("Create New Lead from Web Form - Starts"); - - if($assigned_user_id == '') - { - //if the user id is empty then assign it to the admin user - $assigned_user_id = $adb->query_result($adb->pquery("select id from vtiger_users where user_name=?", array('admin')),0,'id'); - } - - require_once("modules/Leads/Leads.php"); - $focus = new Leads(); - $focus->column_fields['lastname'] = $lastname; - $focus->column_fields['email'] = trim($email); - $focus->column_fields['phone'] = $phone; - $focus->column_fields['company'] = $company; - $focus->column_fields['country'] = $country; - $focus->column_fields['description'] = $description; - $focus->column_fields['assigned_user_id'] = $assigned_user_id; - - $focus->save("Leads"); - //$focus->retrieve_entity_info($focus->id,"Leads"); - - $adb->println("Create New Lead from Web Form - Ends"); - - if($focus->id != '') - $msg = 'Thank you for your interest. Information has been successfully added as Lead in vtigerCRM.'; - else - $msg = "Lead creation failed. Please try again"; - - return $msg; -} - -/** function used to create contact from webform from the passed details - * @param string $first_name - first name to create contact - * @param string $last_name - last name to create contact - * @param string $email_address - email address to create contact - * @param string $home_phone - phone number of home to create contact - * @param string $department - department to create contact - * @param string $description - description to create contact - * @param int $assigned_user_id - assigned to user for the contact - * return message success or failure about the contact creation - */ -function create_contact_from_webform($first_name, $last_name, $email_address, $home_phone, $department,$description, $assigned_user_id) -{ - global $adb; - - $adb->println("Create New Contact from Web Form - Starts"); - if($assigned_user_id == '') - { - //if the user id is empty then assign it to the admin user - $assigned_user_id = $adb->query_result($adb->pquery("select id from vtiger_users where user_name=?", array('admin')),0,'id'); - } - - require_once('modules/Contacts/Contacts.php'); - $focus = new Contacts(); - - $focus->column_fields['firstname'] = $first_name; - $focus->column_fields['lastname'] = $last_name; - $focus->column_fields['email'] = trim($email_address); - $focus->column_fields['homephone'] = $home_phone; - $focus->column_fields['department'] = $department; - $focus->column_fields['description'] = $description; - $focus->column_fields['assigned_user_id'] = $assigned_user_id; - - $focus->save("Contacts"); - //$focus->retrieve_entity_info($focus->id,"Contacts"); - - $adb->println("Create New Contact from Web Form - Ends"); - - if($focus->id != '') - $msg = 'Thank you for your interest. Information has been successfully added as Contact in vtigerCRM.'; - else - $msg = "Contact creation failed. Please try again"; - - return $msg; -} - -/** function used to unsubscribe the mail - * @param string $emailid - email address to unsubscribe - * return message about the success or failure status about the unsubscribe - */ -function unsubscribe_email($emailid) -{ - global $adb; - $adb->println("Enter into the function unsubscribe_email($emailid)"); - - $emailid = trim($emailid); - - $contact_res = $adb->pquery("select emailoptout from vtiger_contactdetails where email=?", array($emailid)); - $contact_noofrows = $adb->num_rows($contact_res); - $emailoptout = $adb->query_result($contact_res,0,'emailoptout'); - - if($contact_noofrows > 0) - { - if($emailoptout != 1) - { - $adb->pquery("update vtiger_contactdetails set emailoptout=1 where email=?", array($emailid)); - $msg = "You have been unsubscribed."; - } - else - { - $msg = "You are already unsubscribed."; - } - } - else - { - $msg = "There are no record available for this mail address."; - } - - $adb->println("Exit from the function unsubscribe_email($emailid)"); - return $msg; -} - - -//$log->fatal("In soap.php"); - -/* Begin the HTTP listener service and exit. */ -$server->service($HTTP_RAW_POST_DATA); - -exit(); - - - -?> diff --git a/themes/alphagrey/style.css b/themes/alphagrey/style.css index b8977c3..93d922e 100644 --- a/themes/alphagrey/style.css +++ b/themes/alphagrey/style.css @@ -1942,7 +1942,7 @@ textarea { border-left:1px solid #eaeaea; border-top:1px solid #eaeaea; border-right:1px solid #999; - border-left:1px solid #999;; + border-left:1px solid #999; } .mailClientCSSButton { @@ -2398,7 +2398,7 @@ div.goog-te-sectional-gadget-all{ bottom: 0; background: url(images/help_header.png) repeat-x; border-top:2px solid #717351; - heigth:30px; + height:30px; } div#vtigerHelpPopupLay{ @@ -2475,7 +2475,7 @@ input { font-weight: bold; } .mm_message p { - border: 2px solid #AAAAAA;; + border: 2px solid #AAAAAA; padding: 2px; position: fixed; left: 50%; @@ -2648,7 +2648,7 @@ a.allMnu:Hover{ } .searchBtn{ width:48px; - height:31px; + height:24px; } .selectall{ diff --git a/themes/bluelagoon/style.css b/themes/bluelagoon/style.css index 83238d7..d533a11 100644 --- a/themes/bluelagoon/style.css +++ b/themes/bluelagoon/style.css @@ -1900,7 +1900,7 @@ textarea { border-left:1px solid #eaeaea; border-top:1px solid #eaeaea; border-right:1px solid #939271; - border-left:1px solid #939271;; + border-left:1px solid #939271; } .mailClientCSSButton { @@ -2391,7 +2391,7 @@ vtigerHelpWelcomePopupLay #contentOfHelp{ bottom: 0; background: url(images/help_header.png) repeat-x; border-top:2px solid #717351; - heigth:30px; + height:30px; } div#vtigerHelpPopupLay{ position : relative !important; @@ -2465,7 +2465,7 @@ input { font-weight: bold; } .mm_message p { - border: 2px solid #4F94CD;; + border: 2px solid #4F94CD; padding: 2px; position: fixed; left: 50%; @@ -2652,7 +2652,7 @@ a.allMnu:Hover{ } .searchBtn{ width:48px; - height:31px; + height:24px; } .selectall{ diff --git a/themes/softed/style.css b/themes/softed/style.css index 452fd27..375a603 100644 --- a/themes/softed/style.css +++ b/themes/softed/style.css @@ -2038,7 +2038,7 @@ textarea { border-left:1px solid #eaeaea; border-top:1px solid #eaeaea; border-right:1px solid #939271; - border-left:1px solid #939271;; + border-left:1px solid #939271; } .mailClientCSSButton { @@ -2536,7 +2536,7 @@ div.goog-te-sectional-gadget-all{ bottom: 0; background: url(images/help_header.png) repeat-x; border-top:2px solid #717351; - heigth:30px; + height:30px; } div#vtigerHelpPopupLay{ position : relative !important; @@ -2824,7 +2824,7 @@ a.allMnu:Hover{ } .searchBtn{ width:48px; - height:31px; + height:24px; } .selectall{ diff --git a/themes/woodspice/style.css b/themes/woodspice/style.css index 565c179..ba30286 100644 --- a/themes/woodspice/style.css +++ b/themes/woodspice/style.css @@ -1993,7 +1993,7 @@ textarea { border-left:1px solid #eaeaea; border-top:1px solid #eaeaea; border-right:1px solid #939271; - border-left:1px solid #939271;; + border-left:1px solid #939271 } .mailClientCSSButton { @@ -2426,7 +2426,7 @@ div.goog-te-sectional-gadget-all{ bottom: 0; background: url(images/help_header.png) repeat-x; border-top:2px solid #717351; - heigth:30px; + height:30px; } div#vtigerHelpPopupLay{ position : relative !important; @@ -2669,7 +2669,7 @@ a.drop_down_usersettings_name{ } .searchBtn{ width:48px; - height:31px; + height:24px; } .selectall{ diff --git a/upgrade2coreBOS.php b/upgrade2coreBOS.php new file mode 100644 index 0000000..1a67f34 --- /dev/null +++ b/upgrade2coreBOS.php @@ -0,0 +1,152 @@ +'; +echo "vtlib $moduleTitle"; +echo ''; +echo ''; +echo ''; +echo '
    '; +echo ''; +echo "

    $moduleTitle

    "; +echo '
    '; +echo 'coreBOS'; +echo '
    '; +echo '
    '; + +// Turn on debugging level +$Vtiger_Utils_Log = true; + +require_once 'include/utils/utils.php'; +include_once('vtlib/Vtiger/Module.php'); +require 'modules/com_vtiger_workflow/VTEntityMethodManager.inc'; +global $current_user,$adb; +set_time_limit(0); +ini_set('memory_limit','1024M'); + +$current_user = new Users(); +$current_user->retrieveCurrentUserInfoFromFile(1); // admin +if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') { + $current_language = $_SESSION['authenticated_user_language']; +} else { + if(!empty($current_user->language)) { + $current_language = $current_user->language; + } else { + $current_language = $default_language; + } +} +$app_strings = return_application_language($current_language); + +$query_count=0; +$success_query_count=0; +$failure_query_count=0; +$success_query_array=array(); +$failure_query_array=array(); + +function ExecuteQuery($query) { + global $adb,$log; + global $query_count, $success_query_count, $failure_query_count, $success_query_array, $failure_query_array; + + $status = $adb->query($query); + $query_count++; + if(is_object($status)) { + echo ' +
    '.get_class($status).' S '.$query.'
    '.$status.' F '.$query.'
    '.$msg.'
    "; + +ExecuteQuery("update vtiger_field set block=67 where tabid=23 and columnname='s_h_amount'"); +ExecuteQuery("ALTER TABLE vtiger_loginhistory CHANGE user_name user_name VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL"); + +$delimg = array('include/images/AppStore.png', + 'include/images/AppStoreQRCode.png', + 'include/images/ExchangeConnector.png', + 'include/images/GooglePlay.png', + 'include/images/GooglePlayQRCode.png', + 'include/images/OutlookPlugin.png', + 'include/images/vtigercrm_icon.ico', + 'themes/alphagrey/images/vtiger-crm.gif', + 'themes/bluelagoon/images/vtiger-crm.gif', + 'themes/images/aboutUS.jpg', + 'themes/images/bullets.gif', + 'themes/images/honestCRM.gif', + 'themes/images/honestCRMTop.gif', + 'themes/images/loginTopHeaderBg.gif', + 'themes/images/loginTopHeaderName.gif', + 'themes/images/loginTopVersion.gif', + 'themes/images/vtiger-paw.jpg', + 'themes/images/vtiger.jpg', + 'themes/images/vtigerName.gif', + 'themes/images/vtigercrm_icon.ico', + 'themes/images/vtigerlogo.jpg', + 'themes/softed/images/vtiger-crm.gif', + 'themes/woodspice/images/vtiger-crm.gif', + 'test/logo/vtiger-crm-logo.gif', +); +foreach ($delimg as $dimg) { + @unlink($dimg); + putmsg("image $dimg deleted"); +} + +?> +
    +

    +Failed Queries Log +
    + '.$failed_query.''; + ?> +
    +

    + + + + + + + + + + + + + +
    + Total Number of queries executed : + + +
    + Queries Successed : + + + + +
    + Queries Failed : + + + + +
    + + diff --git a/vtigerversion.php b/vtigerversion.php index b520150..9aec5d2 100644 --- a/vtigerversion.php +++ b/vtigerversion.php @@ -11,5 +11,7 @@ $patch_version = ''; $modified_database = ''; $vtiger_current_version = '5.4.0'; $_SESSION['vtiger_version'] = $vtiger_current_version; - +$coreBOS_app_version = '1.0'; +$coreBOS_app_name ='coreBOS'; +$coreBOS_app_url = 'http://corebos.org'; ?> \ No newline at end of file diff --git a/vtlib/ModuleDir/5.4.0/ModuleFile.php b/vtlib/ModuleDir/5.4.0/ModuleFile.php index a608b41..1c97b04 100755 --- a/vtlib/ModuleDir/5.4.0/ModuleFile.php +++ b/vtlib/ModuleDir/5.4.0/ModuleFile.php @@ -267,6 +267,7 @@ class ModuleClass extends CRMEntity { " WHERE uitype='10' AND vtiger_fieldmodulerel.module=?", array($thismodule)); $linkedFieldsCount = $this->db->num_rows($linkedModulesQuery); + $rel_mods[$this->table_name] = 1; for($i=0; $i<$linkedFieldsCount; $i++) { $related_module = $this->db->query_result($linkedModulesQuery, $i, 'relmodule'); $fieldname = $this->db->query_result($linkedModulesQuery, $i, 'fieldname'); @@ -275,7 +276,17 @@ class ModuleClass extends CRMEntity { $other = CRMEntity::getInstance($related_module); vtlib_setup_modulevars($related_module, $other); - $query .= " LEFT JOIN $other->table_name ON $other->table_name.$other->table_index = $this->table_name.$columnname"; + if($rel_mods[$other->table_name]) { + $rel_mods[$other->table_name] = $rel_mods[$other->table_name] + 1; + $alias = $other->table_name.$rel_mods[$other->table_name]; + $query_append = "as $alias"; + } else { + $alias = $other->table_name; + $query_append = ''; + $rel_mods[$other->table_name] = 1; + } + + $query .= " LEFT JOIN $other->table_name $query_append ON $alias.$other->table_index = $this->table_name.$columnname"; } $query .= $this->getNonAdminAccessControlQuery($thismodule,$current_user); diff --git a/vtlib/Vtiger/Mailer.php b/vtlib/Vtiger/Mailer.php index 34971f5..842ac3d 100644 --- a/vtlib/Vtiger/Mailer.php +++ b/vtlib/Vtiger/Mailer.php @@ -57,7 +57,7 @@ class Vtiger_Mailer extends PHPMailer { $this->ConfigSenderInfo($adb->query_result($result, 0, 'from_email_field')); $this->_serverConfigured = true; - $this->Sender= getReturnPath($this->Host); + $this->Sender= getReturnPath($this->Host, $this->From); } }